An interesting note. As you might already know, C# doesn't define the endiannes and it depends on the cpu architecture, if you are writing cross platform/architecture applications you can check with the method call BitConverter.IsLittleEndian
Indicates the byte order ("endianness") in which data is stored in
this computer architecture.
Remarks
Different computer architectures store data using different byte
orders. "Big-endian" means the most significant byte is on the left
end of a word. "Little-endian" means the most significant byte is on
the right end of a word.
Note
You can convert from network byte order to the byte order of the host
computer without retrieving the value of the
BitConverter.IsLittleEndian
field by passing a 16-bit, 32-bit, or 64
bit integer to the IPAddress.HostToNetworkOrder
method.
If you need different endiannes, you can convert easily enough with Array.Reverse
.
byte[] bytes = BitConverter.GetBytes(num);
Array.Reverse(bytes, 0, bytes.Length);
or bitwise switch with types like int
and long
, you could take it a step further with unsafe and pointers for other types
public uint SwapBytes(uint x)
{
x = (x >> 16) | (x << 16);
return ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8);
}
public ulong SwapBytes(ulong x)
{
x = (x >> 32) | (x << 32);
x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16);
return ((x & 0xFF00FF00FF00FF00) >> 8) | ((x & 0x00FF00FF00FF00FF) << 8);
}