简体   繁体   English

类型转换为整数

[英]type cast to integer

Suppose I have 假设我有

    unsigned char * buffer; // buffer len in 10000

I want to convert buffer+50 to buffer+54 to int. 我想将buffer + 50转换为buffer + 54转换为int。 The following code works 以下代码有效

    int c=(*((int *) (buffer+ 32));

But is there any better way to do this and how much instruction it should take ? 但是,有什么更好的方法可以做到这一点,它应该接受多少指令?

Thanks a lot. 非常感谢。

Something like this would work: 这样的事情会起作用:

std::uint32_t convert_to_int32(std::uint8_t* buffer) // assume size 4
{
    std::uint32_t result = (static_cast<std::uint32_t>(buffer[0]) << 24) |
                           (static_cast<std::uint32_t>(buffer[1]) << 16) |
                           (static_cast<std::uint32_t>(buffer[2]) << 8) |
                           (static_cast<std::uint32_t>(buffer[3]));
    return result;
}

The main problem you will have with your current method is if you run into alignment issues (eg you attempt to cast the integer pointer from a point in the buffer that is not on an integer alignment barrier). 当前方法的主要问题是是否遇到对齐问题(例如,尝试从缓冲区中不在整数对齐障碍物上的某个点强制转换整数指针)。 The shifting method gets around that. 移位方法可以解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 type cast CryptoPP :: Integer to int - type cast CryptoPP::Integer to int 如何将 integer 值转换为双倍宽度的类型? - How to cast an integer value to a type with double width? 如何处理警告:从较小的整数类型int广播到int * - How to process the warning:cast to int* from smaller integer type int 如何编写一个基于整数/枚举的模板以转换为模板化类型 - How to write a template to cast to a templatized type based on an integer / enum 在无符号字符到 integer 类型转换的背景中发生了什么? - What's happening in the background of a unsigned char to integer type cast? 从整数到枚举的首选转换样式QEvent :: Type - Prefered cast style from integer to enum QEvent::Type c ++ armadillo cast / convert to integer type vector或matrix - c++ armadillo cast/convert to integer type vector or matrix 我应该使用哪个* _cast将任意整数类型的指针转​​换为char指针? - Which *_cast should I use to cast an arbitrary integer-type pointer to a char pointer? 从 double 到 integer 的显式类型转换是否总是检查整数溢出? - Does explicit type cast from double to integer always check for integer overflow? 当整数类型转换为浮点类型或反之亦然时,C ++会发生什么? - What happens in C++ when an integer type is cast to a floating point type or vice-versa?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM