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