How do I convert between big-endian and little-endian values in C++?
EDIT: For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.
EDIT #2: The answer I accepted applies directly to compilers I'm targetting (which is why I chose it). However, there are other very good, more portable answers here.
With the below given codes you can swap between BigEndian and LittleEndian easily
I am really surprised no one mentioned htobeXX and betohXX functions. They are defined in endian.h and are very similar to network functions htonXX.
I recently wrote a macro to do this in C, but it's equally valid in C++:
It accepts any type and reverses the bytes in the passed argument. Example usages:
Which prints:
The above is perfectly copy/paste-able, but there's a lot going on here, so I'll break down how it works piece by piece:
The first notable thing is that the entire macro is encased in a
do while(0)
block. This is a common idiom to allow normal semicolon use after the macro.Next up is the use of a variable named
REVERSE_BYTES
as thefor
loop's counter. The name of the macro itself is used as a variable name to ensure that it doesn't clash with any other symbols that may be in scope wherever the macro is used. Since the name is being used within the macro's expansion, it won't be expanded again when used as a variable name here.Within the
for
loop, there are two bytes being referenced and XOR swapped (so a temporary variable name is not required):__VA_ARGS__
represents whatever was given to the macro, and is used to increase the flexibility of what may be passed in (albeit not by much). The address of this argument is then taken and cast to anunsigned char
pointer to permit the swapping of its bytes via array[]
subscripting.The final peculiar point is the lack of
{}
braces. They aren't necessary because all of the steps in each swap are joined with the comma operator, making them one statement.Finally, it's worth noting that this is not the ideal approach if speed is a top priority. If this is an important factor, some of the type-specific macros or platform-specific directives referenced in other answers are likely a better option. This approach, however, is portable to all types, all major platforms, and both the C and C++ languages.
Try
Boost::endian
, and DO NOT IMPLEMENT IT YOURSELF!Here's a link
Look up bit shifting, as this is basically all you need to do to swap from little -> big endian. Then depending on the bit size, you change how you do the bit shifting.
If you are doing this for purposes of network/host compatability you should use:
If you are doing this for some other reason one of the byte_swap solutions presented here would work just fine.