Converting right alighed Bytes from integers

  • Thread starter Thread starter Govind
  • Start date Start date
G

Govind

Hi All,
I want to Convert 32 bit integers to byte in right alighed format .

For 32 = the usual way is BitConverter.GetBytes(int32)==> xx xx 00 00 , but
i want right aligned like 00 00 xx xx.Is there any way.

Regards,

Govind.
 
Hi,
Hi All,
I want to Convert 32 bit integers to byte in right alighed format .

For 32 = the usual way is BitConverter.GetBytes(int32)==> xx xx 00 00 , but
i want right aligned like 00 00 xx xx.Is there any way.

// sample

int myInt=456789;
byte[] byteTab=BitConverter.GetBytes(myInt);
Array.Reverse(byteTab);

// now your byte table is reversed

Regards

Marcin
 
IPAddress class in System.Net namespace also has functions for swapping the
byte orders of short, int, and long.

int netOrder = IPAddress.HostToNetworkOrder(val1);
int hostOrder = IPAddress.HostToNetworkOrder(val2);

For any other type you have to revervse the Byte[] yourself as Marcin
indicated. You want to be carefull that the machine uses the expected byte
ordering that you are converting to. This is handled for you in IPAddress
class.
For instance if you reverse the array, be sure to check the byte order of
the machine first. You may not need to reverse it - "network byte order" is
Big Endian.

Here's a sample of converting a double to and from network order:

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


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