And*_*ewR 7 c++ bit-manipulation extract
我在char []数组中有大量的二进制数据,我需要将其解释为打包的6位值数组.
我可以坐下来写一些代码来做这件事,但我认为必须有一个好的现存的类或函数已经有人写过.
我需要的是:
int get_bits(char* data, unsigned bitOffset, unsigned numBits);
Run Code Online (Sandbox Code Playgroud)
所以我可以通过调用以下方法获取数据中的第7个6位字符:
const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
Run Code Online (Sandbox Code Playgroud)
这可能不适用于大于 8 的大小,具体取决于字节序系统。这基本上是 Marco 发布的内容,尽管我不完全确定他为什么一次收集一点。
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;
}
Run Code Online (Sandbox Code Playgroud)