BitArray MyProblem Or Bug ?
My Problem is BitArray (System.Collentions.BitArray)
if you run the code below
byte
[] bits =newbyte[2];bits[0] = 1;
bits[1] = 3;
BitArray BA =
new BitArray(bits);string st =string.Empty;for(int i=0; i< 16; i++)st += Convert.ToInt16(BA.Get(i)).ToString();
MessageBox.Show(st);
the code will create byte array with to bytes
first byte will be: "00000001"(binary view of 1) and the second: "00000011" (binary view of 3)
and the we add this two byte to a bitarray the result of bitArray will be "1000000011000000" as you can see BitArray Class invese the bytes "10000000" ( IS NOT BINARY VIEW OF 1) and "11000000" (is not binary view of 3)
as you can see if you inverse all the BA (BitArray) it will be "0000001100000001" And it's not our number either
i don't know if it's bug or there other way to creating BitArray class. i have runed the code in both VS.NET 2003 And VS.NET 2005 even in VB both the result is the sam
[1468 byte] By [
HamedJI] at [2007-12-25]
Read MSDN topic BitArray Constructor (Byte[]):
The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on.
You can see that bytes are added to bit array in the reverse order.
as i said using "for(int i = 15; i>=0; i--)" won't solve the problem.
if you look closer you'll see the "for" you wrote will produce "0000001100000001" but the true bits are: "0000000100000011".
Constructor first use the first byte and then use second byte it's true but inverse them it's false.
Thank's nobugz for his link
but if it's the problem of this class. it can produce more bigger problems
for example when you save a long(int64) value and load it as two int32 or 4 bytes your data will broke completly you save one think and you load another think completly diffrent with what you have saved
Bit order depend of the processor. You must convert the order only if the processor use little endian.
Try this to convert from int16 and from bigendian
public static Byte[] FromInt16ToByteArray(Int16 number)
{
Byte[] ouByte = BitConverter.GetBytes(number);
if (BitConverter.IsLittleEndian) { Array.Reverse(ouByte); }return ouByte;
}public static Int16 FromByteArrayToInt16(Byte[] number)
{
if (BitConverter.IsLittleEndian) { Array.Reverse(number); }return BitConverter.ToInt16(number,0);
}