从Byte*到unsigned int的memcpy正在反转字节顺序

memcpy from Byte * to unsigned int Is Reversing Byte Order

本文关键字:顺序 字节 memcpy Byte unsigned int      更新时间:2023-10-16

我有一个CFBitVector,看起来像'100000000000000'我将字节数组传递给CFBitVectorGetBits,然后它包含来自该CFBitVector的值。在这个调用之后,bytes[2]看起来像:

bytes[0] == '0x80'
bytes[1] == '0x00'

这正是我所期望的。然而,当将bytes[2]的内容复制到unsigned int bytesValue,时,该值为128,而该值应为32768。十进制值CCD_ 10由十六进制值0x0080表示。本质上,在执行memcpy时,字节顺序似乎是颠倒的。这是怎么回事?这只是endianness的问题吗?

感谢

CFMutableBitVectorRef bitVector = CFBitVectorCreateMutable(kCFAllocatorDefault, 16);
CFBitVectorSetCount(bitVector, 16);
CFBitVectorSetBitAtIndex(bitVector, 0, 1);
CFRange range = CFRangeMake(0, 16);
Byte bytes[2] = {0,0};
unsigned int bytesValue = 0;
CFBitVectorGetBits(bitVector, range, bytes);
memcpy(&bytesValue, bytes, sizeof(bytes));
return bytesValue;

这是怎么回事?这只是endianness的问题吗?

是的。

你的电脑很小。16位值32768在存储器中表示为:

00 80

在一台小型endian机器上。您有:

80 00

相反,正如你所看到的,代表128。