How to convert Bit Array to byte , when bit array has only 5 bits or 6bits

醉酒当歌 提交于 2019-12-25 04:25:03

问题


I have already wrote a program to this , bits working only if bit array length is multiples of 8 . Can some one help me to get bit array of 5 bits converted into byte

both functions work only when it have bit array in multiple of 8 .

public static byte[] BitArrayToByteArray(BitArray bits)
        {
            byte[] ret = new byte[bits.Length / 8];
            bits.CopyTo(ret, 0);
            return ret;
        }


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

回答1:


Basically you need to round up the number of bytes needed in your first method:

byte[] ret = new byte[(bits.Length + 7) / 8];
bits.CopyTo(ret, 0);

Your second method already looks okay at first glance... it certainly fills the right number of bytes. It may not fill them in the way you want it to, but in that case you need to provide more detail about how you expect it to be filled. You may want to just change the initial value of bitIndex for example. (Sample input and output would be immensely useful.)



来源:https://stackoverflow.com/questions/22719893/how-to-convert-bit-array-to-byte-when-bit-array-has-only-5-bits-or-6bits

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