UINT16 value appears to be “backwards” when printi

2020-07-26 17:45发布

I have a UINT8 pointer mArray, which is being assigned information via a *(UINT16 *) casting. EG:

int offset = someValue;
UINT16 mUINT16 = 0xAAFF
*(UINT16 *)&mArray[offset] = mUINT16;

for(int i = 0; i < mArrayLength; i++)
{
    printf("%02X",*(mArray + i));
}

output:   ... FF AA ...
expected: ... AA FF ...

The value I am expecting to be printed when it reaches offset is to be AA FF, but the value that is printed is FF AA, and for the life of me I can't figure out why.

标签: c++
4条回答
在下西门庆
2楼-- · 2020-07-26 17:58

You are probably using a computer that uses a "little-endian" representation of numbers in memory (such as Intel x86 architecture). Basically this means that the least significant byte of any value will be stored at the lowest address of the memory location that is used to store the values. See Wikipdia for details.

In your case, the number 0xAAFF consists of the two bytes 0xAA and 0xFF with 0xFF being the least significant one. Hence, a little-endian machine will store 0xFF at the lowest address and then 0xAA. Hence, if you interpret the memory location to which you have written an UINT16 value as an UINT8, you will get the byte written to that location which happens to be 0xFF

If you want to write an array of UINT16 values into an appropriately sized array of UINT8 values such that the output will match your expectations you could do it in the following way:

/* copy inItems UINT16 values from inArray to outArray in
 * MSB first (big-endian) order 
 */
void copyBigEndianArray(UINT16 *inArray, size_t inItems, UINT8 *outArray)
{
    for (int i = 0; i < inItems; i++)
    {
        // shift one byte right: AAFF -> 00AA
        outArray[2*i]     = inArray[i] >> 8; 

        // cut off left byte in conversion: AAFF -> FF
        outArray[2*i + 1] = inArray[i]       
    }
}

You might also want to check out the hton*/ntoh*-family of functions if they are available on your platform.

查看更多
混吃等死
3楼-- · 2020-07-26 18:04

You didn't specify but I'm guessing your mArray is an array of bytes instead of an array of UINT16s. You're also running on a little-endian machine. On little endian machines the bytes are stored in the opposite order of big-endian machines. Big endians store them pretty much the way humans read them.

查看更多
何必那么认真
4楼-- · 2020-07-26 18:06

It's because your computer's CPU is using little endian representation of integers in memory

查看更多
家丑人穷心不美
5楼-- · 2020-07-26 18:08

You are using a little endian machine.

查看更多
登录 后发表回答