Converting C# byte to BitArray
Asked Answered
F

4

18

Is there any predefined function available to convert a byte into BitArray?

One way would be to inspect every bit of the byte value and then perform bitwise operation. I was wondering if there is any way which is more straightforward than this.

Feuchtwanger answered 26/6, 2012 at 9:46 Comment(2)
You should rephrase your question. Do you want to convert byte or byte array to System.Collections.BitArray?Ludicrous
my exact situation is to convert 3 bytes from a byte Array. The method described below would work for me.Feuchtwanger
P
45

Yes, using the appropriate BitArray() constructor as described here:

var bits = new BitArray(arrayOfBytes);

You can call it with new BitArray(new byte[] { yourBite }) to create an array of one byte.

Papke answered 26/6, 2012 at 9:48 Comment(1)
how about three bytes at a time, say something like: new BitArray(new byte[] { myBite1, myBite2, myBite2 })Feuchtwanger
P
8

if you have a byte number or even an integer, etc.

BitArray myBA = new BitArray(BitConverter.GetBytes(myNumber).ToArray());

Note: you need a reference to System.Linq

Penumbra answered 1/11, 2012 at 16:51 Comment(0)
C
3

Solution is simple, just two instructions (which are marked in following code), simply convert byte to binary using Convert.ToString(btindx,2), zero pad the resultant string to 8 bits (or lengths 8),strBin.PadLeft(8,'0'); and concatenate all binary strings to form a bit stream of your byte array, If you like, you can also form an array of strings to separate each byte's binary representation.

    byte[] bt = new byte[2] {1,2};

    string strBin =string.Empty;
    byte btindx = 0;
    string strAllbin = string.Empty;

    for (int i = 0; i < bt.Length; i++)
    {
        btindx = bt[i];

        strBin = Convert.ToString(btindx,2); // Convert from Byte to Bin
        strBin = strBin.PadLeft(8,'0');  // Zero Pad

        strAllbin += strBin;
    }
Chinachinaberry answered 13/10, 2016 at 13:16 Comment(0)
G
1

If the length of the BitArray in question is not intended to be a multiple of the number of bits in a byte (8) you can do something like this to ensure the correct number of bits when converting from byte[] to BitArray:

public static byte[] ToByteArray (this BitArray bits) {
    byte[] ret = new byte[(bits.Length - 1) / 8 + 1];
    bits.CopyTo (ret, 0);
    return ret;
}

public static BitArray ToBitArray (this byte[] bytes, int bitCount) {
    BitArray ba = new BitArray (bitCount);
    for (int i = 0; i < bitCount; ++i) {
        ba.Set (i, ((bytes[i / 8] >> (i % 8)) & 0x01) > 0);
    }
    return ba;
}
Gladiator answered 21/8, 2020 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.