N/Direct - The .NET Interoperability Resource Center 

FAQ

 

 

 

Most Valuable Professional

How do I copy a numeric variable to a byte array or vice versa?
Written: 6/16/2002 Updated: 3/25/2003

There are a couple different options. The easiest is probably to use the System.BitConverter class.

C#
float f = 123.45F;
byte[] bytes = BitConverter.GetBytes( f );
// Prints: 66 E6 F6 42
Console.WriteLine( "{0:X} {1:X} {2:X} {3:X}", bytes[0], bytes[1], bytes[2], bytes[3] );
f = BitConverter.ToSingle( bytes, 0 );
// Prints: 123.45
Console.WriteLine( f );
    

VB.NET
Dim f As Single = 123.45
Dim bytes() As Byte = BitConverter.GetBytes( f )
' Prints: 66 E6 F6 42
Console.WriteLine( "{0:X} {1:X} {2:X} {3:X}", bytes(0), bytes(1), bytes(2), bytes(3) )
f = BitConverter.ToSingle( bytes, 0 )
' Prints: 123.45
Console.WriteLine( f )
    

For integer types, it can also be easily done with manually by ORing, ANDing and shifting.

C#
byte[] bytes = new byte[] {152, 186, 220, 254};
int i;
i = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
// Prints: FEDCBA98
Console.WriteLine( i.ToString( "X" ) );
bytes[0] = (byte)(i & 0xFF);
bytes[1] = (byte)((i>>8) & 0xFF);
bytes[2] = (byte)((i>>16) & 0xFF);
bytes[3] = (byte)((i>>24) & 0xFF);
// Prints: FE DC BA 98
Console.WriteLine( "{0:X} {1:X} {2:X} {3:X}", bytes[3], bytes[2], bytes[1], bytes[0] );
    

VB.NET
' Compile with /removeintchecks, or check "Remove integer overflow checks" in VS.NET.
Dim bytes() As Byte = {152, 186, 220, 254}
Dim i As Integer
i = bytes(3) * &H1000000 Or bytes(2) * &H10000 Or bytes(1) * &H100 Or bytes(0)
' Prints: FEDCBA98
Console.WriteLine( i.ToString( "X" ) )
#If VB_NET_71  ' VB.NET 7.1/VS.NET 2003 or later
    bytes(0) = CByte(i And &HFF)
    bytes(1) = CByte((i >> 8) And &HFF)
    bytes(2) = CByte((i >> 16) And &HFF)
    bytes(3) = CByte((i >> 24) And &HFF)
#Else
    bytes(0) = CByte(i And &HFF)
    bytes(1) = CByte((i And &HFF00) \ &H100)
    bytes(2) = CByte((i And &HFF0000) \ &H10000)
    bytes(3) = CByte((i And &HFF000000) \ &H1000000)
#End If
' Prints: FE DC BA 98
Console.WriteLine( "{0:X} {1:X} {2:X} {3:X}", bytes(3), bytes(2), bytes(1), bytes(0) )
    

And finally, in C#, you have the option to do it with pointers in an unsafe code block.

C#
byte[] bytes = new byte[] {152, 186, 220, 254};
int i;
unsafe {
  fixed( byte* pb = bytes ) {
    i = *((int*)pb);
    *((int*)pb) = 0x4030201;
  }
  // Prints: FEDCBA98
  Console.WriteLine( i.ToString( "X" ) );
  // Prints: 1 2 3 4
  Console.WriteLine( "{0:X} {1:X} {2:X} {3:X}", bytes[0], bytes[1], bytes[2], bytes[3] );
}