Little Endian - Big Endian Problem

江枫思渺然 提交于 2019-12-01 06:49:42
  • Are you printing the result correctly?
  • Does the fact that you're passing in a reference instead of a value make a difference?

Your code seems to be correct.

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

#include <cstdio>

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

Eliminate the ampersand in front of the x in your argument specifier. You want to pass the value.

Have you unit-tested your code?

On my platform, this passes:

void LittleEndianTest::testLittleEndian()
{
    unsigned int x = 0x31014950;
    unsigned int result = 
         (
             ( (x & 0x000000FF) << 24 ) + 
             ( (x & 0x0000FF00) << 8  ) +
             ( (x & 0x00FF0000) >> 8  ) +
             ( (x & 0xFF000000) >> 24 ) 
         );

    CPPUNIT_ASSERT_EQUAL((unsigned int)0x50490131, result); 
}

The example in your edit is outputting y not r. The input y is, of course, not modified.

If I run the code you posted, it gives the correct result: endian_swap ( 0x31014950 ) == 0x50490131.

To get the result: endian_swap ( 0x31014950 ) == 0x54110131, your code must be equivalent to this:

#define __
inline unsigned int endian_swap(unsigned int& x)  
{                  //0x31014950  ->            0x54110131
    return  ( ( (x & 0x000000FF) << 24 ) |   //  50
        __    ( (x & 0x00F0F000) << 12 ) |   //   4
        __    ( (x & 0x00FF0000) << 4  ) |   //    1  
        __    ( (x & 0x00FF0000) << 0  ) |   //     1  
        __    ( (x & 0x00FF0000) >> 8  ) |   //      01
        __    ( (x & 0xFF000000) >> 24 ) );  //        31        
}

Check you haven't got similar differences in your code too.

Bit operators are not useful because they operates as if the bits are arranged in order from least significant bit to most significant bit regardless of the true internal byte order.

void isBigEndian()
{
    void *number;
    number = (int *) new int(0x01000010);
    // 0x01000010
    //   01 00 00 10                                      Hexadecimal
    //   0    1      0    0      0    0       1    0
    //   0000 0001   0000 0000   0000 0000    0001 0000   Bit
    //   1           0           0            16          Decimal
    char *byte;
    byte = (char *)number;
    cout << static_cast<int>(*byte);//prints 16: Little Endian
}

You change the number above and make it return 1 when it is BigEndian.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!