By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,968 Members | 1,844 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,968 IT Pros & Developers. It's quick & easy.

Converting right alighed Bytes from integers

P: n/a
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.

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Hi,

Govind wrote:
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

Jul 19 '05 #2

P: n/a
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

"Govind" <go******@interworldgroup.com> wrote in message
news:OP**************@TK2MSFTNGP12.phx.gbl...
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.


Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.