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

前端 未结 3 527
庸人自扰
庸人自扰 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:50

    This may not work for sizes greater than 8, depending on endian system. It's basically what Marco posted, though I'm not entirely sure why he'd gather one bit at a time.

    int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {
        numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course
        data += bitOffset/8;
        bitOffset %= 8;
        return (*((int*)data) >> bitOffset) & numBits;  //little endian
        //return (flip(data[0]) >> bitOffset) & numBits; //big endian
    }
    
    //flips from big to little or vice versa
    int flip(int x) {
        char temp, *t = (char*)&x;
        temp = t[0];
        t[0] = t[3];
        t[3] = temp;
        temp = t[1];
        t[1] = t[2];
        t[2] = temp;
        return x;
    }
    

提交回复
热议问题