C/C++ Code to treat a character array as a bitstream

前端 未结 3 504
庸人自扰
庸人自扰 2020-12-28 11:18

I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values.

I could sit down and write some code to do

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 11:56

    I think something in the line of the following might work.

    int get_bit(char *data, unsigned bitoffset) // returns the n-th bit
    {
        int c = (int)(data[bitoffset >> 3]); // X>>3 is X/8
        int bitmask = 1 << (bitoffset & 7);  // X&7 is X%8
        return ((c & bitmask)!=0) ? 1 : 0;
    }
    
    int get_bits(char* data, unsigned bitOffset, unsigned numBits)
    {
        int bits = 0;
        for (int currentbit = bitOffset; currentbit < bitOffset + numBits; currentbit++)
        {
            bits = bits << 1;
            bits = bits | get_bit(data, currentbit);
        }
        return bits;
    }
    

    I've not debugged nor tested it, but you can use it as a start point.

    Also, take into account bit order. You might want to change

        int bitmask = 1 << (bitoffset & 7);  // X&7 is X%8
    

    to

        int bitmask = 1 << (7 - (bitoffset & 7));  // X&7 is X%8
    

    depending on how the bit array has been generated.

提交回复
热议问题