Convert bool[] to byte[]

前端 未结 7 1758
野趣味
野趣味 2020-12-09 06:32

I have a List which I want to convert to a byte[]. How do i do this? list.toArray() creates a bool[].

7条回答
  •  暖寄归人
    2020-12-09 06:34

    Or the IEnumerable approach to AnorZaken's answer:

    static IEnumerable PackBools(IEnumerable bools)
    {
        int bitIndex = 0;
        byte currentByte = 0;
        foreach (bool val in bools) {
            if (val)
                currentByte |= (byte)(1 << bitIndex);
            if (++bitIndex == 8) {
                yield return currentByte;
                bitIndex = 0;
                currentByte = 0;
            }
        }
        if (bitIndex != 8) {
            yield return currentByte;
        }
    }
    

    And the according unpacking where paddingEnd means the amount of bits to discard from the last byte to unpack:

    static IEnumerable UnpackBools(IEnumerable bytes, int paddingEnd = 0)
    {
        using (var enumerator = bytes.GetEnumerator()) {
            bool last = !enumerator.MoveNext();
            while (!last) {
                byte current = enumerator.Current;
                last = !enumerator.MoveNext();
                for (int i = 0; i < 8 - (last ? paddingEnd : 0); i++) {
                    yield return (current & (1 << i)) != 0;
                }
            }
        }
    }
    

提交回复
热议问题