提取和组合来自不同字节的位c c ++ [英] Extract and combine bits from different bytes c c++

查看:192
本文介绍了提取和组合来自不同字节的位c c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了一个字节数组:

I have declared an array of bytes:

uint8_t memory[123];

其中已填写:

memory[0]=0xFF;
memory[1]=0x00;
memory[2]=0xFF;
memory[3]=0x00;
memory[4]=0xFF;

现在我从用户那里得到特定位的请求。例如,我接收到发送位置10:35的位的请求,并且我必须返回以字节组合的那些位。在这种情况下,我需要4个字节包含。

And now i get requests from the user for specific bits. For example, i receive a request to send the bits in position 10:35, and i must return those bits combined in bytes. In that case i would need 4 bytes which contain.

response[0]=0b11000000;
responde[1]=0b00111111;
response[2]=0b11000000; 
response[3]=0b00000011; //padded with zeros for excess bits

这将用于Modbus,这是一个大端协议。我想出了以下代码:

This will be used for Modbus which is a big-endian protocol. I have come up with the following code:

for(int j=findByteINIT;j<(findByteFINAL);j++){

   aux[0]=(unsigned char) (memory[j]>>(startingbit-(8*findByteINIT)));
   aux[1]=(unsigned char) (memory[j+1]<<(startingbit-(8*findByteINIT)));

   response[h]=(unsigned char) (aux[0] | aux[1] );
   h++;

   aux[0]=0x00;//clean aux
   aux[1]=0x00;

        }

这不工作,但应该接近理想的解决方案。任何建议?

which does not work but should be close to the ideal solution. Any suggestions?

推荐答案

我认为这应该可以。

int start_bit = 10, end_bit = 35; // input

int start_byte = start_bit / CHAR_BIT;
int shift = start_bit % CHAR_BIT;
int response_size = (end_bit - start_bit + (CHAR_BIT - 1)) / CHAR_BIT;
int zero_padding = response_size * CHAR_BIT - (end_bit - start_bit + 1);

for (int i = 0; i < response_size; ++i) {
  response[i] =
      static_cast<uint8_t>((memory[start_byte + i] >> shift) |
                           (memory[start_byte + i + 1] << (CHAR_BIT - shift)));
}
response[response_size - 1] &= static_cast<uint8_t>(~0) >> zero_padding;






如果输入是起始位和数字的位而不是起始位和(包括)结束位,则可以使用完全相同的代码,但使用以下计算上面的 end_bit

int start_bit = 10, count = 9;  // input
int end_bit = start_bit + count - 1;

这篇关于提取和组合来自不同字节的位c c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆