C# 将bit位数据拼装为byte

public class BitWriter
    {
        private byte[] m_data = null;
        private int m_dataLen = 0;
        private int m_pos = 0;
        private BitArray bit_data = null;

        public BitWriter(int len)
        {
            m_dataLen = len;
            m_data = new byte[len];
            Array.Clear(m_data, 0, len);

            bit_data = new BitArray(len * 8);
        }

        public void Write(int data, int size)
        {
            //将传入数据转换成二进制位
            int[] value = new int[1] { data };
            BitArray bit_temp = new BitArray(value);

            for (int i = 0; i < size; i++)
            {
                bit_data[m_pos + i] = bit_temp[size - i - 1];
            }          

            m_pos += size;
        }

        public byte[] GetData()
        {
            for (int i = 0, y = 0; i < bit_data.Length / 8; i++)
            {
                m_data[i] = 0;

                if(bit_data[y])
                    m_data[i] |= (byte)(1 << 7);

                if (bit_data[y + 1])
                    m_data[i] |= (byte)(1 << 6);

                if (bit_data[y + 2])
                    m_data[i] |= (byte)(1 << 5);

                if (bit_data[y + 3])
                    m_data[i] |= (byte)(1 << 4);

                if (bit_data[y + 4])
                    m_data[i] |= (byte)(1 << 3);

                if (bit_data[y + 5])
                    m_data[i] |= (byte)(1 << 2);

                if (bit_data[y + 6])
                    m_data[i] |= (byte)(1 << 1);

                if (bit_data[y + 7])
                    m_data[i] |= (byte)(1);

                y += 8;
            }
            
            return m_data;
        }
    }

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页