Little vs Big Endianess: How to interpret the test

前端 未结 6 952
长发绾君心
长发绾君心 2020-12-11 03:44

So I\'m writing a program to test the endianess of a machine and print it. I understand the difference between little and big endian, however, from what I\'ve found online,

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 04:01

    If a big-endian 4-byte unsigned integer looks like 0xAABBCCDD which is equal to 2864434397, then that same 4-byte unsigned integer looks like 0xDDCCBBAA on a little-endian processor which is also equal to 2864434397.

    If a big-endian 2-byte unsigned short looks like 0xAABB which is equal to 43707, then that same 2-byte unsigned short looks like 0xBBAA on a little-endian processor which is also equal to 43707.

    Here are a couple of handy #define functions to swap bytes from little-endian to big-endian and vice-versa -->

    // can be used for short, unsigned short, word, unsigned word (2-byte types)
    #define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))
    
    // can be used for int or unsigned int or float (4-byte types)
    #define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))
    
    // can be used for unsigned long long or double (8-byte types)
    #define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))
    

提交回复
热议问题