C# 將bit位資料拼裝為byte

Just4life發表於2016-08-18
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;
        }
    }

相關文章