字节数组转bool数组

问题描述 投票:0回答:2

我想接收一个字节[]并将其转换为一个bool[]。我已经找到了一个代码,它可以将bool放到一个bool队列中,但我不具备必要的技能知识,无法从一个给我一个bool队列的方法变成一个给我一个bool数组的方法。

任何帮助都是感激的

public void TmsTdiEnqueue(int bitCount, byte[] byteArray)
        {
            // New TAP bit queues with allocated number of bits
            boolQueue = new Queue<bool>(bitCount);

            // Fill bool queue
            int byteIndex = 0;
            int bitMask = 0x01;
            for (int i = 0; i < bitCount; i++)
            {
                boolQueue.Enqueue((tmsBytes[byteIndex] & bitMask) != 0);
                IncrementBitPointer(ref byteIndex, ref bitMask);
            }
        }

        private void IncrementBitPointer(ref int byteIndex, ref int bitMask)
        {
            byteIndex += (bitMask == 0x80) ? 1 : 0;
            bitMask = (bitMask == 0x80) ? 0x01 : bitMask << 1;
        }
c# arrays
2个回答
2
投票

如果源码 byte[] 数组每个位有一个布尔值,你可以简单地使用 BitArray 类。

BitArray ba = new BitArray(new byte[] { 1, 2, 3 });
bool[] ret = new bool[ba.Length];
ba.CopyTo(ret, 0);

1
投票

你可以用 SelectMany 来实现这一目标。首先,先用一个方法将单个的 byte 到一系列的 bool:

static bool[] ByteToBools(byte value)
{
    var values = new bool[8];

    values[0] = (value & 1) == 0 ? false : true;
    values[1] = (value & 2) == 0 ? false : true;
    values[2] = (value & 4) == 0 ? false : true;
    values[3] = (value & 8) == 0 ? false : true;
    values[4] = (value & 16) == 0 ? false : true;
    values[5] = (value & 32) == 0 ? false : true;
    values[6] = (value & 64) == 0 ? false : true;
    values[7] = (value & 128) == 0 ? false : true;

    return values;
}

现在我们只是 SelectMany在...上byte 数组,对于每个字节,我们调用 ByteToBools:

var numbers = new byte[]{1, 2, 3, 5, 255};

var bits = numbers.SelectMany(number => ByteToBools(number));
foreach(var bit in bits)
{
    Console.WriteLine(bit);
}
© www.soinside.com 2019 - 2024. All rights reserved.