繁体   English   中英

从“m”个字节中获取“n”个位数

[英]Get "n" number of bits from "m" number of bytes

我在从特定字节中提取特定数量的位时遇到问题。 假设我们有这样的情况:

(我假设我从 0 开始计算字节/位)我从 stream 接收 3 个字节,并想从第 1 个字节的第 7 位开始读取 11 位:在第 2 个字节的第 5 位完成,我想将它存储在某个地方

一些可视化:

     0th byte          1st byte         2nd byte
|7|6|5|4|3|2|1|0|#|7|6|5|4|3|2|1|0|#|7|6|5|4|3|2|1|0|
                   ^ ^ ^ ^ ^ ^ ^ ^   ^ ^ ^

我知道位移是 go 的方向,但我缺乏这方面的经验,我真的很好奇有经验的开发人员的意见

编辑:很抱歉之前没有指定它 - 语言是 C++,但我不能使用像“bitset”这样的库。

“n”和“m”可以是任何数字,例如:n = 17 m = 5。另一个假设是数据需要是连续的 - 这意味着最后我需要有例如 11 位的连续数据.

我想做的是这样的:

buf[0] << ((byteCount - 1) - index) * stepWidth;

这给了我完整的第一个/第二个字节。 最后读取的位应该“合并”为一个变量,类似于:

int buf[1] = variable with 8 bits;
int buf[2] = variable with 3 bits;
mergedBuf  = buf[1] + buf[1] // "+" means merging, not adding values

C++ 在标准库中有很好的 class :

https://www.cplusplus.com/reference/bitset/bitset/

如果 C 是这种情况,可以使用位掩码和 &(与)操作。 喜欢:

unsigned char buf[3]; // let's say this is your buffer;
int _2nd_byte_value = buf[1] & 0xFF; // since you want to get all bits of 2nd byte;
int _3rd_byte_value = (buf[2] & 0xE0) >> 5; // first mask then shift; 

然后,您可以根据需要操作这些值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM