我有一个List<bool>,我想将其转换为byte[]。我该怎么做呢?list.toArray()创建一个bool[]

最佳答案

这是两种方法,具体取决于您是要将位打包成字节还是要具有与原始位一样多的字节:

    bool[] bools = { true, false, true, false, false, true, false, true,
                     true };

    // basic - same count
    byte[] arr1 = Array.ConvertAll(bools, b => b ? (byte)1 : (byte)0);

    // pack (in this case, using the first bool as the lsb - if you want
    // the first bool as the msb, reverse things ;-p)
    int bytes = bools.Length / 8;
    if ((bools.Length % 8) != 0) bytes++;
    byte[] arr2 = new byte[bytes];
    int bitIndex = 0, byteIndex = 0;
    for (int i = 0; i < bools.Length; i++)
    {
        if (bools[i])
        {
            arr2[byteIndex] |= (byte)(((byte)1) << bitIndex);
        }
        bitIndex++;
        if (bitIndex == 8)
        {
            bitIndex = 0;
            byteIndex++;
        }
    }

关于c# - 将bool []转换为byte [],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/713057/

10-10 22:44