Convert Byte Array to Bit Array?

只愿长相守 提交于 2019-11-29 16:02:42

问题


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


回答1:


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

BitArray bits = new BitArray(arrayOfBytes);



回答2:


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;
    }
}



回答3:


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;
}



回答4:


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);



回答5:


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();
}


来源:https://stackoverflow.com/questions/2548018/convert-byte-array-to-bit-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!