read from stream in Big Endian order

  • Thread starter Thread starter Laszlo Szijarto
  • Start date Start date
L

Laszlo Szijarto

I guess this follows an earlier question. Is there a way to read from a
stream, using a Binary Reader, in Big Endian order -- i.e., if I call, for
example, ReadUInt32 that it would suck out 4 bytes and then turn them into
an Int in Big Endian instead of the Windows native Little Endian?

Thank you,
Laszlo
 
There are overloads in the IPAddress class for converting to and from
network byte ordering.

IPAddress.NetworkToHostOrder(int);
IPAddress.NetworkToHostOrder(short);
IPAddress.NetworkToHostOrder(long);

IPAddress.HostToNetworkOrder(int);
IPAddress.HostToNetworkOrder(short);
IPAddress.HostToNetworkOrder(long);

For all other data types you have to flip it yourself, but be sure to check
the byte order of the machine first...

private static double NetworkToHostOrder(byte[] data)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
return BitConverter.ToDouble(data, 0);
}

private static byte[] HostToNetworkOrder(double d)
{
byte[] data = BitConverter.GetBytes(d);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
return data;
}

HTH;
Eric Cadwell
http://www.origincontrols.com
 
Back
Top