How can I reverse the byte order of an int? [closed]

亡梦爱人 提交于 2020-04-06 03:52:07

问题


I am having a hard time converting this ActionScript code to C#. I don't understand how I can mimic what ByteArray() is doing in C#. If anyone could help me recreate this functionality I would really appreciate it.

ActionScript (seed is a uint.):

//Start by reversing the byte order of the seed
var ba:ByteArray = new ByteArray();
ba.endian = Endian.BIG_ENDIAN;
ba.writeInt(seed);
ba.position = 0;
ba.endian = Endian.LITTLE_ENDIAN;
seed = ba.readInt();

回答1:


You can use BitConverter.GetBytes(UInt32) to get your byte[], then call Array.Reverse on the array, then use BitConverter.ToUInt32(byte[]) to get your int back out.

Edit

Here's a more efficient and cryptic way to do it:

public static UInt32 ReverseBytes(UInt32 value)
{
     return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
         (value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}

This is what you need to know to understand what's happening here:

  1. A UInt32 is 4 bytes.
  2. In hex, two characters represent one byte. 179 in decimal == B3 in hex == 10110011 in binary.
  3. A bitwise and (&) preserves the bits that are set in both inputs: 1011 0011 & 1111 0000 = 1011 0000; in hex: B3 & F0 = B0.
  4. A bitwise or (|) preserves the bits that are set in either input: 1111 0000 | 0000 1111 = 1111 1111; in hex, F0 | 0F = FF.
  5. The bitwise shift operators (<< and >>) move the bits left or right in a value. So 0011 1100 << 2 = 1111 0000, and 1100 0011 << 4 = 0011 0000.

So value & 0x000000FFU returns a UInt32 with all but the 4th byte set to 0. Then << 24 moves that 4th byte to the left 24 places, making it the 1st byte. Then (value & 0x0000FF00U) << 8 zeros out everything but the 3rd byte and shifts it left so it is the second byte. And so on. The four (x & y) << z create four UInt32s where each of the bytes have been moved to the place they will be in the reversed value. Finally, the | combines those UIntt32s bytes back together into a single value.



来源:https://stackoverflow.com/questions/18145667/how-can-i-reverse-the-byte-order-of-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!