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

Discussion in 'Programming' started by ASRRAJ, Mar 24, 2010.

  1. ASRRAJ

    ASRRAJ New Member

    Joined:
    Jun 13, 2008
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    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);
    }
     
    Last edited by a moderator: Mar 24, 2010

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice