Little Endian - Big Endian Problem

后端 未结 7 611
你的背包
你的背包 2021-01-13 14:15

Little Endian vs Big Endian

Big Endian = 0x31014950
Little Endian = 0x50490131

However Using this Method

inline unsigned int endian         


        
7条回答
  •  青春惊慌失措
    2021-01-13 14:49

    Your code seems to be correct.

    The following program (http://ideone.com/a5TBF):

    #include 
    
    inline unsigned int endian_swap(unsigned const int& x)  
    {
    return ( ( (x & 0x000000FF) << 24 ) | 
             ( (x & 0x0000FF00) << 8  ) |
             ( (x & 0x00FF0000) >> 8  ) |
             ( (x & 0xFF000000) >> 24 ) );
    }
    
    int main()
    {
        unsigned int x = 0x12345678;
        unsigned int y = endian_swap(x);
        printf("%x %x\n", x, y);
        return 0;
    }
    

    outputs:

    12345678 78563412


    Edit:
    you need std::cout << std::hex << r, otherwise you are printing (1) wrong variable, and (2) in decimal :-)

    See this example: http://ideone.com/EPFz8

提交回复
热议问题