stb*_*tra 4 c parsing bit-fields
我有一个只能以8位字节寻址的数据流,我想把它解析成6位元素并将其存储到数组中.有没有最知名的方法来做到这一点?
11110000 10101010 11001100
Run Code Online (Sandbox Code Playgroud)
成
像一个数组
111100|001010|101011|001100
Run Code Online (Sandbox Code Playgroud)
(可以零填充,只需要通过这种方式寻址)
数据是一个8位数组,也是6位的倍数,不是真的无穷无尽
取决于一个字节在您的特定体系结构上有多少位.在六位架构上它很简单:-)
假设每字节8位架构,您将不得不做一些事情:
int sixbits(unsigned char* datastream, unsigned int n) {
int bitpos = n*6;
return (datastream[bitpos/8] >> bitpos%8) // lower part of the five bit group
+ (datastream[bitpos/8+1] << 8-bitpos%8) // if bitpos%8>2, we need to add some carry bits from the next char
& 0x3f; // and finally mask the lowest 6 bits
}
Run Code Online (Sandbox Code Playgroud)
其中n是第n个6位组.任何体面的编译器都会用移位替换除法,用ands替换模数.只需在循环中使用此函数即可填充目标数组.