位操作-C/C++代码,将字符数组视为位流
bit manipulation - C/C++ Code to treat a character array as a bitstream
我在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
这取决于比特阵列是如何生成的。
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符