Byte Array to Value Pattern

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

 

Pattern Syntax

 

 

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;

}

 

 

Remarks

This design pattern:

 

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

 

 

See Also

Value to Byte Array Pattern

Building Packets

Design Patterns Index