Swap Bytes to Network Order Pattern

This design pattern converts multibyte values between host and network byte-order.

 

Pattern Syntax

 

 

using System.Net;

 

private Int16 SwapBytes( Int16 h )

{

   // swap the bytes of a signed 16-bit integer

   Int16 n = System.Net.IPAddress.HostToNetworkOrder( h );

   return n;

}

 

private UInt16 SwapBytes( UInt16 h )

{

   // swap the bytes of an unsigned 16-bit integer

   UInt16 n = (UInt16)System.Net.IPAddress.HostToNetworkOrder( (Int16)h );

   return n;

}

 

private Int32 SwapBytes( Int32 h )

{

   // swap the bytes of a signed 32-bit integer

   Int32 n = System.Net.IPAddress.HostToNetworkOrder( h );

   return n;

}

 

private UInt32 SwapBytes( UInt32 h )

{

   // swap the bytes of an unsigned 32-bit integer

   UInt32 n = (UInt32)System.Net.IPAddress.HostToNetworkOrder( (Int32)h );

   return n;

}

 

 

Remarks

This design pattern:

 

Note

The "directionality" of the HostToNetworkOrder method is not relevant: the SwapBytes methods can also be used to convert network to host byte-ordered values.

 

See Also

Building Packets

Design Patterns Index