[英]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.