C#  •  Convert Between Integers and Byte Arrays

Listing 1. You can convert an int to a byte array, and vice versa, in three ways: with the BitConverter class, with manual bit shifting, or by doing a direct memory copy.

using System;

// Compile with /unsafe option

class Test
{
   static void Main()
   {
      uint u = 0xba5eba11;
      byte[] b = new byte[] {0xfe, 0x5a, 0x11, 0xfa};

      Console.WriteLine( "Using BitConverter, 
         IsLittleEndian=" + 
         BitConverter.IsLittleEndian );
      byte[] b2 = BitConverter.GetBytes( 0xba5eba11 );
      PrintByteArray( b2 );
      uint u2 = BitConverter.ToUInt32( b, 0 );
      Console.WriteLine( "0x{0:x}", u2 );

      Console.WriteLine( "Using shift operators" );
      b2 = new byte[4];
      b2[0] = (byte)(u);
      b2[1] = (byte)(u >> 8);
      b2[2] = (byte)(u >> 16);
      b2[3] = (byte)(u >> 24);
      PrintByteArray( b2 );
      u2 = (uint)(b[0] | b[1] << 8 | b[2] << 16 | b[3] << 
         24);
      Console.WriteLine( "0x{0:x}", u2 );

      Console.WriteLine( "Using pointers in unsafe code" 
         );
      unsafe {
         b2 = new byte[4];
         fixed ( byte* pb2 = b2 )
            *((uint*)pb2) = u;
         PrintByteArray( b2 );
         fixed ( byte* pb = b )
            u2 = *((uint*)pb);
         Console.WriteLine( "0x{0:x}", u2 );
      }
   }

   static void PrintByteArray(byte[] ba)
   {
      foreach ( byte b in ba )
         Console.Write( "0x{0:x2} ", b );
      Console.WriteLine();
   }
}