char bytes[2];
bytes[0] = 0; //0x00
bytes[1] = 24; //0x18
uint16_t* ptrU16 = (uint16_t*)bytes; // I expect it points to the memory block: 0x18
cout << *ptrU16 << endl; // I expect 24, but it is 6144
我的代码有什么问题?
最佳答案
你有一个小端机器。 6144
是 0x1800
。当你的机器在内存中表示 16 位值 0x0018
时,它会将 0x18
字节放在第一位,然后是 0x00
字节,所以当你解释两个字节序列 0x0018
作为 uint16_t
,它给你 6144
(即 0x1800
),而不是 24
(即 0x0018
)。
如果您更改为:
bytes[0] = 24;
bytes[1] = 0;
您很可能会看到预期的结果。
如果你真的想得到你期望的结果,那么你要么必须手动计算它,例如:
uint16_t n = (bytes[1] << 8) + bytes[0];
或者,更一般地说:
char bytes[] = {0x18, 0x00};
uint16_t n = 0;
for ( size_t i = 0; i < 2; ++i ) {
n += bytes[i] << 8 * i;
}
std::cout << n << std::endl;
或者您可以使用像 ntohs()
这样的函数,因为网络字节顺序是大端。
关于c++ - 如何通过转换类型指针将 char 数组转换为 uint16_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27558956/