This design pattern converts multibyte values between host and network byte-order.
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;
}
This design pattern:
declares four overloaded private methods called SwapBytes,
the parameter h is converted using the System.Net.IPAddress.HostToNetworkOrder method, and returned,
where h is an unsigned type the value is cast before and after.
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.