byte order and endianness

G

Guest

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
 
J

Jon Skeet [C# MVP]

Senthil said:
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.
 

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