Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Programming (http://www.go4expert.com/forums/programming-forum/)
-   -   How do I convert between big-endian and little-endian values? (http://www.go4expert.com/forums/i-convert-endian-little-endian-values-t21478/)

ASRRAJ 24Mar2010 11:26

How do I convert between big-endian and little-endian values?
 
The operations are the same in both directions. Here is some code for the common unsigned data types:
Code:

inline void endian_swap(unsigned short& x)
{
    x = (x>>8) |
        (x<<8);
}

inline void endian_swap(unsigned int& x)
{
    x = (x>>24) |
        ((x<<8) & 0x00FF0000) |
        ((x>>8) & 0x0000FF00) |
        (x<<24);
}

// __int64 for MSVC, "long long" for gcc
inline void endian_swap(unsigned __int64& x)
{
    x = (x>>56) |
        ((x<<40) & 0x00FF000000000000) |
        ((x<<24) & 0x0000FF0000000000) |
        ((x<<8)  & 0x000000FF00000000) |
        ((x>>8)  & 0x00000000FF000000) |
        ((x>>24) & 0x0000000000FF0000) |
        ((x>>40) & 0x000000000000FF00) |
        (x<<56);
}



All times are GMT +5.5. The time now is 23:04.