How do I convert between big-endian and little-endian values in C++?

前端 未结 30 2522
难免孤独
难免孤独 2020-11-21 23:18

How do I convert between big-endian and little-endian values in C++?

EDIT: For clarity, I have to translate binary data (double-precision floating point values and 3

30条回答
  •  北海茫月
    2020-11-22 00:11

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

    If a big-endian 16-bit unsigned short looks like 0xAABB which is equal to 43707, then that same 16-bit 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))
    

提交回复
热议问题