当位数组只有5位或6位时,如何将位数组转换为字节 [英] How to convert Bit Array to byte , when bit array has only 5 bits or 6bits

查看:105
本文介绍了当位数组只有5位或6位时,如何将位数组转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为此编写了一个程序,仅当位数组长度是8的倍数时,位才有效。
有人能帮助我将5位的位数组转换为字节吗?

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

这两个函数仅在其位数组为8的倍数时才起作用。

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


推荐答案

基本上,您需要四舍五入第一种方法所需的字节数:

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

您的第二种方法乍看之下已经可以了,它肯定可以填充正确的字节数。它可能无法按照您希望的方式填充它们,但是在这种情况下,您需要提供有关如何填充的更多详细信息。例如,您可能只想更改 bitIndex 的初始值。 (示例输入和输出将非常有用。)

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.)

这篇关于当位数组只有5位或6位时,如何将位数组转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆