C code to convert endianness?
I want to convert an unsigned 32-bit integer as follows:
Input = 0xdeadbeef
Output = 0xfeebdaed
Thank you.
That's not an endianness conversion. The output should be 0xEFBEADDE
, not 0xFEEBDAED
. (Only the bytes are swapped, and each byte is 2 hexadecimal digits.)
For converting between little- and big-endian, take a look at _byteswap_ulong.
The general process for nibble reversal is:
((i & 0xF0000000)>>28) | ((i & 0xF000000)>>20) | ((i & 0xF00000)>>12) | ..... | ((i & 0xF)<<28)
Mask, shift, or (I hope I got the numbers right):
- Extract the portion of the number you're interested in by ANDing (&) with a mask.
- Shift it to it's target location with the >> and << operations.
- Construct the new value by ORing (|) the pieces together.
If you want to reorder bytes you will mask with 0xFF. As everyone is saying that's probably what you want and if you're looking for a canned version follow other people's suggestions.
精彩评论