简体   繁体   中英

Byte[] to BitArray and back to Byte[]

As the title states, i'm trying to convert a byte array to bit array back to byte array again.

I am aware that Array.CopyTo() takes care of that but the byte array received is not the same as the original one due to how BitArray stores values in LSB.

How do you go about it in C#?

This should do it

static byte[] ConvertToByte(BitArray bits) {
    // Make sure we have enough space allocated even when number of bits is not a multiple of 8
    var bytes = new byte[(bits.Length - 1) / 8 + 1];
    bits.CopyTo(bytes, 0);
    return bytes;
}

You can verify it using a simple driver program like below

// test to make sure it works
static void Main(string[] args) {
    var bytes = new byte[] { 10, 12, 200, 255, 0 };
    var bits = new BitArray(bytes);
    var newBytes = ConvertToByte(bits);

    if (bytes.SequenceEqual(newBytes))
        Console.WriteLine("Successfully converted byte[] to bits and then back to byte[]");
    else
        Console.WriteLine("Conversion Problem");
}

I know that the OP is aware of the Array.CopyTo solution (which is similar to what I have here), but I don't see why it's causing any Bit order issues. FYI, I am using .NET 4.5.2 to verify it. And hence I have provided the test case to confirm the results

To get a BitArray of byte[] you can simply use the constructor of BitArray :

BitArray bits = new BitArray(bytes);

To get the byte[] of the BitArray there are many possible solutions. I think a very elegant solution is to use the BitArray.CopyTo method. Just create a new array and copy the bits into:

byte[]resultBytes = new byte[(bits.Length - 1) / 8 + 1];
bits.CopyTo(resultBytes, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM