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

byte order and endianness

P: n/a
Iam trying to pack some bits and create a client request packet using a
Byte[] array. To test the "endianess" I tried a small sample and used the
BitConverter to print the actual values ... and the out does not seem right
..... the sample code and the output is shown below.

What Am I missing here ?

using System;
....
byte b = 10;
uint val = b;
Byte[] packet = BitConverter.GetBytes(b);

BitArray array = new
BitArray(packet);

IEnumerator enumerator = array.GetEnumerator();

string value = null;
int width = 8;

if(BitConverter.IsLittleEndian)
Console.WriteLine("Little Endian order.");
else
Console.WriteLine("Big Endian order.");

while(enumerator.MoveNext())
{
if(width == 0)
{
Console.Write(" ");
width = 8;
}

value = (enumerator.Current.ToString() == Boolean.TrueString)?"1":"0";
Console.Write(value);
width--;
}
Output
=========

Little Endian order.
01010000 00000000

Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Senthil <Se*****@discussions.microsoft.com> wrote:
Iam trying to pack some bits and create a client request packet using a
Byte[] array. To test the "endianess" I tried a small sample and used the
BitConverter to print the actual values ... and the out does not seem right
.... the sample code and the output is shown below.

What Am I missing here ?


BitArray doesn't work the way you think it does. From the docs for the
constructor of BitArray you're using:

<quote>
The first byte in the array represents bits 0 through 7, the second
byte represents bits 8 through 15, and so on. The Least Significant Bit
of each byte represents the lowest index value: " bytes [0] & 1"
represents bit 0, " bytes [0] & 2" represents bit 1, " bytes [0] & 4"
represents bit 2, and so on.
</quote>

And that's eactly what you're seeing. Byte 0 is 10, and byte 1 is 0.
That means that bit 0 of your bit array is 0, bit 1 is 1 (which is
bytes[0] & 2), bit 2 is 0, bit 3 is 1 (which is bytes[0] & 8) etc.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.