如何将最低有效位写入缓冲区?

时间:2013-08-23 06:43:29

标签: c++

我有一个writeBit方法,它应该将int i的最低有效位写入char类型的缓冲区buff,然后递增位缓冲区索引。 我不确定我所拥有的是否正确,任何意见都表示赞赏。

private:
char buff;    // buffer
int num_bits; // num of bits written to buff
std::ostream& os_ref;

public:
// Skipping the constructor and ostream& for brevity

int writeBit(int i) {
  // flush buffer if full
  if(num_bits == 8)
  flush();

  // write least significant bit into the buffer at the current index.
  int lb = i & 1;
  buff = buff & num_bits;  // not sure about this line
  buff = lb;
  num_bits++;

  // return current index
  return num_bits; // do I return nbits as current index?
}

3 个答案:

答案 0 :(得分:0)

我猜这个应该工作,让我知道:

buff |= (i & 1) << nbits;

确保buff期间flush()设置为0 基本上,i & 1得到最后一个有效位,<< nbits移动左侧 nbits 次的位,此位被添加到 buff

答案 1 :(得分:0)

假设flush将num_bits设置为零:

char unmask = ~(1 << num_bits);
buf &= unmask;
buf |= (i & 1) << num_bits;
++num_bits;
如果num_bits的位始终为零,那么@ Michael的答案会更好。

答案 2 :(得分:0)

获取uint32_t的最低位:

uint32_t i = 1337;
uint8_t lsb = i & 1; // zeroes out all bits except first
buffer |= (lsb << num_bits); // shifts the lsb by num_bits to left and then ORs it into the char field

注意:出于兼容性原因,我使用uint32_t代替unsigned int