This design pattern converts a multibyte integer value to an array of bytes.
private byte[] ValueToByteArray( Int16 val )
{
// convert a signed 16-bit integer to a two byte array
return System.BitConverter.GetBytes( val );
}
private byte[] ValueToByteArray( UInt16 val )
{
// convert an unsigned 16-bit integer to a two byte array
return System.BitConverter.GetBytes( val );
}
private byte[] ValueToByteArray( Int32 val )
{
// convert a signed 32-bit integer to a four byte array
return System.BitConverter.GetBytes( val );
}
private byte[] ValueToByteArray( UInt32 val )
{
// convert an unsigned 32-bit integer to a four byte array
return System.BitConverter.GetBytes( val );
}
This design pattern:
defines four overloaded private methods called ValueToByteArray,
the integer value is converted to a byte array using the System.BitConverter.GetBytes method and returned,
Note
The resultant bytes are in host byte order: if the protocol requires them in network byte order, the bytes of the input value or 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 the conversion is performed, ie:
// swap the bytes before conversion
return System.BitConverter.GetBytes( SwapBytes( val ) );