C / C ++ code对待一个字符数组为比特流 [英] C/C++ Code to treat a character array as a bitstream
问题描述
我有二进制数据的一个char []数组一大坨,我需要间preT外带6位值的数组。
我的可能的坐下来写一些code这样做,但我想有必须有一个良好的现存类或函数有人已经写的。
我需要的是这样的:
INT get_bits(字符*数据,符号bitOffset,无符号NUMBITS);
所以我可以通过调用获取数据第七届6位字符:
const的无符号BITSIZE = 6;
焦炭CH =的static_cast<&烧焦GT;(get_bits(数据,7 * BITSIZE,BITSIZE));
这可能不适用于尺寸大于8的工作,这取决于endian系统。这基本上就是马可·贴,虽然我不完全知道为什么他会在一个时间聚集一位。
INT get_bits(字符*数据,无符号整型bitOffset,无符号整型NUMBITS){
NUMBITS = POW(2 NUMBITS) - 1; //这只会工作到32位,当然
数据+ = bitOffset / 8;
bitOffset%= 8;
返回(*(为(int *)数据)GT;> bitOffset)及NUMBITS; //小尾数
//回报(翻转(数据[0])GT;> bitOffset)及NUMBITS; //大端
}//从大翻转很少或反之亦然
INT翻转(INT X){
焦炭温度,* T =(字符*)及X;
TEMP = T [0];
T [0] = T [3];
T [3] =温度;
TEMP = T [1];
T [1] = T [2];
T [2] =温度;
返回X;
}
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 this but I'm thinking there has to be a good extant class or function somebody has written already.
What I need is something like:
int get_bits(char* data, unsigned bitOffset, unsigned numBits);
so I could get the 7th 6-bit character in the data by calling:
const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
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;
}
这篇关于C / C ++ code对待一个字符数组为比特流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!