简体   繁体   中英

UINT16 value appears to be “backwards” when printing

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.

你正在使用一个小端机器。

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.

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.

这是因为你的计算机的CPU在内存中使用整数的小端表示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM