简体   繁体   English

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

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

I have a problem with extracting specific amount of bits from specific bytes.我在从特定字节中提取特定数量的位时遇到问题。 Lets say we have case like:假设我们有这样的情况:

(I assume that I start counting bytes/bits from 0) I receive 3 bytes from stream and want to read 11 bits starting from 1st byte's 7th bit: finishing at 2nd byte's 5nd bit, and I want to store it somewhere (我假设我从 0 开始计算字节/位)我从 stream 接收 3 个字节,并想从第 1 个字节的第 7 位开始读取 11 位:在第 2 个字节的第 5 位完成,我想将它存储在某个地方

Some visualisation:一些可视化:

     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|
                   ^ ^ ^ ^ ^ ^ ^ ^   ^ ^ ^

I know that bit shifting is a direction to go, but I lack experience in that topic, and Im really curious on the opinion from experienced developers我知道位移是 go 的方向,但我缺乏这方面的经验,我真的很好奇有经验的开发人员的意见

EDIT: Sorry for not specifying it before - the language is C++, but I cannot use libraries like "bitset".编辑:很抱歉之前没有指定它 - 语言是 C++,但我不能使用像“bitset”这样的库。

The "n" and "m" can be any number, eg.: n = 17 m = 5. Another assumption is that data will need to be continous - it means that in the end I need to have eg 11 bits of continous data. “n”和“m”可以是任何数字,例如:n = 17 m = 5。另一个假设是数据需要是连续的 - 这意味着最后我需要有例如 11 位的连续数据.

What I was trying to do was something like this:我想做的是这样的:

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

Which gave me full first/second byte.这给了我完整的第一个/第二个字节。 In the end readed bits should be "merged" as one variable, somehing like:最后读取的位应该“合并”为一个变量,类似于:

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++ has nice class in standart library: C++ 在标准库中有很好的 class :

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

If C is the case, you can use bit mask and & (and) operation.如果 C 是这种情况,可以使用位掩码和 &(与)操作。 like:喜欢:

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; 

Then you can manipulate these values as you wish.然后,您可以根据需要操作这些值。

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

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