位操作-C/C++代码,将字符数组视为位流

bit manipulation - C/C++ Code to treat a character array as a bitstream

本文关键字:数组 字符 C++ 代码 位操作      更新时间:2023-10-16

我在char[]数组中有一大块二进制数据,我需要将其解释为压缩的6位值数组。

可以坐下来写一些代码来做这件事,但我认为必须有一个好的现存类或函数已经有人写过了。

我需要的是:

int get_bits(char* data, unsigned bitOffset, unsigned numBits);

这样我就可以通过调用来获得数据中的第7个6位字符

const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));

Boost.DynamicBitset-试试看。

这可能不适用于大于8的大小,具体取决于endian系统。这基本上就是马可发布的内容,尽管我不完全确定他为什么会一次收集一点。

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

我认为下面一行中的内容可能会起作用。

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

我既没有调试也没有测试它,但您可以将它作为一个起点。

此外,还要考虑比特顺序。您可能想要更改

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

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

这取决于比特阵列是如何生成的。