Value to Byte Array Pattern

This design pattern converts a multibyte integer value to an array of bytes.

 

Pattern Syntax

 

 

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 );

}

 

 

Remarks

This design pattern:

 

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 ) );

 

 

See Also

Byte Array to Value Pattern

Building Packets

Design Patterns Index