Convert Byte Array to Bit Array?
Asked Answered
E

6

32

How would I go about converting a bytearray to a bit array?

Elly answered 30/3, 2010 at 19:20 Comment(0)
A
58

The obvious way; using the constructor that takes a byte array:

BitArray bits = new BitArray(arrayOfBytes);
Alula answered 30/3, 2010 at 19:22 Comment(1)
What about to a pre-existing bit array?Monroemonroy
B
16

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;
    }
}
Bustos answered 30/3, 2010 at 19:27 Comment(1)
Your answer is more appropriate than the answer above cos result contains leading zeros. +1Cambell
P
2
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;
}
Parallelogram answered 31/8, 2012 at 11:40 Comment(1)
Just curious.. Doesn't he want the function the other way?!!Sexology
U
1

You can use BitArray to create a stream of bits from a byte array. Here an example:

string testMessage = "This is a test message";

byte[] messageBytes = Encoding.ASCII.GetBytes(testMessage);

BitArray messageBits = new BitArray(messageBytes);
Unlimber answered 20/12, 2017 at 20:29 Comment(0)
H
1
byte number  = 128;
Convert.ToString(number, 2);

=> out: 10000000

Hawkinson answered 6/9, 2020 at 10:44 Comment(2)
Could you please provide a bit more detail of what you are doing and how it is working?Hottempered
From the documentation >ToString(Byte, Int32) Converts the value of an 8-bit unsigned integer to its equivalent string representation in a specified base.Rightward
E
0
public static byte[] ToByteArray(bool[] byteArray)
{
    return = byteArray
               .Select(
                    (val1, idx1) => new { Index = idx1 / 8, Val = (byte)(val1 ? Math.Pow(2, idx1 % 8) : 0) }
                )
                .GroupBy(gb => gb.Index)
                .Select(val2 => (byte)val2.Sum(s => (byte)s.Val))
                .ToArray();
}
Electroluminescence answered 30/3, 2016 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.