4

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#?

zyrkor
  • 73
  • 2
  • 5
  • You could do smth. like https://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c – CShark Aug 18 '17 at 14:46

2 Answers2

4

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

Vikhram
  • 4,294
  • 1
  • 20
  • 32
3

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);
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • won't work if the BitArray has length 0; use instead: var bytes = new byte[(int)Math.Ceiling((double)bits.Length / 8)]; – dmihailescu Jun 28 '19 at 16:33