read from stream in Big Endian order

  • Thread starter Laszlo Szijarto
  • 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
 
E

Eric Cadwell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top