Convert bool[] to byte[]

前端 未结 7 1772
野趣味
野趣味 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:59

    Here's two approaches, depending on whether you want to pack the bits into bytes, or have as many bytes as original bits:

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

提交回复
热议问题