This design pattern converts an array of bytes to an integer value.
private Int16 ByteArrayToInt16( byte[] data )
{
// convert first two bytes of the array to a signed 16-bit integer
Int16 val = System.BitConverter.ToInt16( data, 0 );
return val;
}
private UInt16 ByteArrayToUInt16( byte[] data )
{
// convert first two bytes of the array to an unsigned 16-bit integer
UInt16 val = System.BitConverter.ToUInt16( data, 0 );
return val;
}
private Int32 ByteArrayToInt32( byte[] data )
{
// convert first four bytes of the array to a signed 32-bit integer
Int32 val = System.BitConverter.ToInt32( data, 0 );
return val;
}
private UInt32 ByteArrayToUInt32( byte[] data )
{
// convert first four bytes of the array to an unsigned 32-bit integer
UInt32 val = System.BitConverter.ToUInt32( data, 0 );
return val;
}
This design pattern:
defines four private methods,
each method accepts a byte array parameter called data,
the byte array is converted to an integer value using the System.BitConverter class, and returned,
the method assumes that the byte array contains at least the correct number of bytes for the conversion, and that the bytes to convert are located at the start of the array (index zero).
Note
The methods above also assume that the bytes are in the correct host order: if they are not, the bytes of the converted value must be swapped.
Using the example from the Swap Bytes to Network Order pattern, the bytes in the value can be swapped before being returned, ie:
// swap the bytes
return SwapBytes( val );