从缓冲区中提取一个位

时间:2012-02-22 00:03:06

标签: c++

什么是从无符号字符中提取一点的最好方法。在我看来,我认为这非常有效。

int bit;
  unsigned char buffer;
  bit= 1 & (buffer>>3) //`if i want to extract the fourth bit
  bit=  1 & (buffer>>7)//if i want to extract the 8 bit

1 个答案:

答案 0 :(得分:1)

如果您不关心位在最不重要的位置(例如,因为您需要布尔条件),您可以这样做:

if (buffer & (1<<3)) {
    // ...
}

由于constant folding,这可能会更快:它在运行时只有一个操作而不是两个。

相关问题