开发者

C code to convert endianness?

开发者_如何学C

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):

  1. Extract the portion of the number you're interested in by ANDing (&) with a mask.
  2. Shift it to it's target location with the >> and << operations.
  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜