Reputation: 2221
I'm trying to initialize a System.BitArray instance from integer value. However, it looks like I don't get the right values.
My code is
var b = new BitArray(BitConverter.GetBytes(0xfa2));
for (int i = 0; i < b.Count; i++)
{
char c = b[i] ? '1' : '0';
Console.Write(c);
}
Console.WriteLine();
I've tried also without BitConverter:
var b = new BitArray(new int[] { 0xfa2 });
But none of these attempt seem to work. These are the attempts that was suggested here: Convert int to a bit array in .NET
My output: 01000101111100000000000000000000. The excpected output: 111110100010.
Any help will be really appreciated!
Upvotes: 1
Views: 2980
Reputation: 6024
As stated in documentation BitArray Constructor (Int32[]):
The number in the first values array element represents bits 0 through 31, the second number in the array represents bits 32 through 63, and so on. The Least Significant Bit of each integer represents the lowest index value: " values [0] & 1" represents bit 0, " values [0] & 2" represents bit 1, " values [0] & 4" represents bit 2, and so on.
When use this constructor there no need to check endianness, just reverse output order:
var b = new BitArray(new int[] { 0xfa2 });
// skip leading zeros, but leave least significant bit:
int count = b.Count;
while (count > 1 && !b[count-1])
count--;
// output
for (int i = count - 1; i >= 0; i--)
{
char c = b[i] ? '1' : '0';
Console.Write(c);
}
Console.WriteLine();
Upvotes: 1
Reputation: 6374
This is a Little-Endian vs Big-Endian issue, so you need to take the endienness of the hw architecture into consideration. Also based on the documentation you need to change the way you print the BitArray.
byte[] buffer = BitConverter.GetBytes((ushort)0xfa2);
if (BitConverter.IsLittleEndian) Array.Reverse(buffer);
var b = new BitArray(buffer);
for (int i = 0; i < b.Count; i+=8)
{
for (int j=i + 7; j >= i; j--)
{
char c = b[j] ? '1' : '0';
Console.Write(c);
}
}
Console.WriteLine();
Reference:
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.
Upvotes: 2
Reputation: 141618
You are looping from the wrong direction. Try this:
var b = new BitArray(BitConverter.GetBytes(0xfa2));
for (int i = b.Count-1; i >= 0; i--)
{
char c = b[i] ? '1' : '0';
Console.Write(c);
}
Console.WriteLine();
Upvotes: 5