How would I go about converting a bytearray to a bit array?
6 Answers
The obvious way; using the constructor that takes a byte array:
BitArray bits = new BitArray(arrayOfBytes);
1 Comment
Sir
What about to a pre-existing bit array?
It depends on what you mean by "bit array"... If you mean an instance of the BitArray class, Guffa's answer should work fine.
If you actually want an array of bits, in the form of a bool[] for instance, you could do something like that :
byte[] bytes = ...
bool[] bits = bytes.SelectMany(GetBits).ToArray();
...
IEnumerable<bool> GetBits(byte b)
{
for(int i = 0; i < 8; i++)
{
yield return (b & 0x80) != 0;
b *= 2;
}
}
1 Comment
Nolesh
Your answer is more appropriate than the answer above cos result contains leading zeros. +1
public static byte[] ToByteArray(this BitArray bits)
{
int numBytes = bits.Count / 8;
if (bits.Count % 8 != 0) numBytes++;
byte[] bytes = new byte[numBytes];
int byteIndex = 0, bitIndex = 0;
for (int i = 0; i < bits.Count; i++) {
if (bits[i])
bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));
bitIndex++;
if (bitIndex == 8) {
bitIndex = 0;
byteIndex++;
}
}
return bytes;
}
1 Comment
Antony Thomas
Just curious.. Doesn't he want the function the other way?!!
byte number = 128;
Convert.ToString(number, 2);
=> out: 10000000
2 Comments
darclander
Could you please provide a bit more detail of what you are doing and how it is working?
Francesco B.
From the documentation >ToString(Byte, Int32) Converts the value of an 8-bit unsigned integer to its equivalent string representation in a specified base.