Fastest way to convert int to 4 bytes in C#

A byte* cast using unsafe code is by far the fastest:

    unsafe static void Main(string[] args) {
        int i = 0x12345678;
        byte* pi = (byte*)&i;
        byte lsb = pi[0];  
        // etc..
    }

That's what BitConverter does as well, this code avoids the cost of creating the array.


What is a fastest way to convert int to 4 bytes in C# ?

Using a BitConverter and it's GetBytes overload that takes a 32 bit integer:

int i = 123;
byte[] buffer = BitConverter.GetBytes(i);

The fastest way is with a struct containing 4 bytes.

  • In a defined layout (at byte position 0, 1, 2, 3
  • And an int32 that starts at position 0.
  • Put in the 4 variables, read out the byte.
  • Finished.

Significantly faster than the BitConverter.

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx

has the necessary attribute.

[StructLayout(LayoutKind.Explicit)]
struct FooUnion
{
    [FieldOffset(0)]
    public byte byte0;
    [FieldOffset(1)]
    public byte byte1;
    [FieldOffset(2)]
    public byte byte2;
    [FieldOffset(3)]
    public byte byte3;

    [FieldOffset(0)]
    public int integer;

}