CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Hybrid View

  1. #1
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

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

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

    A: 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 Andreas Masur; July 23rd, 2005 at 12:32 PM.

  2. #2
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245
    Q: Why didn't you just use 'ntohl()' and 'htonl()'?

    A: These functions
    • do not always swap endian-ness and
    • are not always portable.

    For more information please see the FAQ "What do 'ntohl()' and 'htonl()' actually do?".


    Last edited by Andreas Masur; July 23rd, 2005 at 12:32 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured