如何处理个别位?

时间:2012-01-02 23:12:23

标签: c bit-manipulation

  

可能重复:
  Explanation of an algorithm to set, clear and test a single bit

我有unsigned char。我希望将位2到4(从最低有效位计为0)复制到另一个unsigned char作为前三位。例如,在

abcdefgh // a,b,c,d,e,f,g,h are 0 or 1

变为

00000def

我试过了

unsigned char input, output;
output = (input << 3) >> 5;

哪个不起作用,但是

output = (input << 3)
output >>= 5;

确实有效。

C中是否有办法在一行中完成此任务?

3 个答案:

答案 0 :(得分:8)

转移它,然后屏蔽其余部分:

output = ( input >> 2 ) & 0x07;

答案 1 :(得分:2)

这只会获得您想要的位,然后将它们移到右侧。这是@rsaxvc的相反方法。

output = (input & 28) >> 2;

答案 2 :(得分:0)

试试这个:

unsigned char input, output;
input = 0x12abcdef;
output = ((input & 0x00fff000) >> 3) & 0x00000fff;

我不认为你可以在同一条线上来回移动并且假设你每次移动空间都用零填充,但这可能是编译器依赖的,如果你这样做你就会得到正确的东西保证。

我假设“前三位”是指3个最低有效位,即小端系统中最左边或前3位。