追加1到32位数字到字符缓冲区 [英] Append 1 to 32 bit numbers to a char buffer

查看:250
本文介绍了追加1到32位数字到字符缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的char * 缓冲,我想追加各种比特大小的整数( 1 之间 32 )来。

I have a char* buffer, that I want to append integers of various bit sizes (between 1 and 32) to.

因此​​,我需要一个函数:

Thus, I need a function:

void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size);

这是可以移动的,也就是说,对象 13 位到 470 个缓冲位的位置。

that can move an object of, say, 13 bits to the 470th bit position of buffer.

我当然可以由一个位转嫁到缓冲区中的一个,但速度是至关重要的,因此喜欢它似乎应该可以一次移动大块。是否有这样做的标准方法?好像应该有一个标准方法,但一些谷歌上搜索,并因此搜索还没有给我我想要的东西。

I could of course shift the bits onto the buffer one by one, but speed is of the essence so it seems like it should be possible to move larger chunks at a time. Is there a standard method to do this? Seems like there should be a standard method, but some googling and SO searching has not given me what I want.

推荐答案

如何是这样的:

void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size) {
  int* int_buffer = reinterpret_cast<int*>(buffer);

  const int bits_per_int = 8 * sizeof(int);

  int current_int    = bits_appended_so_far / bits_per_int;
  int current_offset = bits_appended_so_far % bits_per_int;

  int_buffer[current_int] |= object << current_offset;
  if( current_offset )
      int_buffer[current_int+1] |= object >> (bits_per_int - current_offset);
}

这假定对象只有设置最低显著 object_bit_size 位,否则,你需要添加一个步骤砍额外的(不必要的)位关闭。它还假定您开始添加位之前缓冲区初始化为零。

This assumes that object only has the least significant object_bit_size bits set, otherwise you need to add a step to chop the extra (unwanted) bits off. It also assumes that buffer is initialized to zeros before you start adding the bits.

这篇关于追加1到32位数字到字符缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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