如何反转int的字节顺序? [英] How can I reverse the byte order of an int?
问题描述
我很难将这个ActionScript代码转换为C#。我不明白如何模仿C#中的ByteArray()。如果有人可以帮助我重新创建此功能,我将不胜感激。
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(种子
是一个uint。) :
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();
推荐答案
您可以使用 BitConverter。 GetBytes(UInt32)
来获取您的 byte []
,然后调用 Array.Reverse
数组,然后使用 BitConverter.ToUInt32(byte [])
将int撤回。
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.
编辑
这是一种更有效,更隐秘的方法:
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:
- UInt32是4个字节。
- 以十六进制表示,两个字符代表一个字节。十进制中的179 ==十六进制中的B3 =二进制中的10110011。
- 按位和(
&
)保留了在两者输入中设置:1011 0011& 1111 0000 = 1011 0000
;以十六进制表示:B3& F0 = B0
。 - 按位或(
|
)保留在任一输入中设置的位:1111 0000 | 0000 1111 = 1111 1111
;以十六进制表示,F0 | 0F = FF
。 - 按位移位运算符(
<<
和>>
)将值左移或右移。因此0011 1100<< 2 = 1111 0000
和1100 0011<< 4 = 0011 0000
。
- A UInt32 is 4 bytes.
- In hex, two characters represent one byte. 179 in decimal == B3 in hex == 10110011 in binary.
- A bitwise and (
&
) preserves the bits that are set in both inputs:1011 0011 & 1111 0000 = 1011 0000
; in hex:B3 & F0 = B0
. - A bitwise or (
|
) preserves the bits that are set in either input:1111 0000 | 0000 1111 = 1111 1111
; in hex,F0 | 0F = FF
. - The bitwise shift operators (
<<
and>>
) move the bits left or right in a value. So0011 1100 << 2 = 1111 0000
, and1100 0011 << 4 = 0011 0000
.
所以 value& 0x000000FFU
返回一个UInt32,除了第4个字节以外的所有字节都设置为0。然后<< 24
将第4个字节向左移24个位置,使其成为第1个字节。然后(值& 0x0000FF00U)<< 8
将第三个字节以外的所有内容清零,然后将其左移,使其成为第二个字节。等等。四个(x& y)<< z
创建四个UInt32,其中每个字节都已移动到它们将处于反转值的位置。最后, |
将这些UIntt32s字节组合回一个单个值。
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.
这篇关于如何反转int的字节顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!