以字节为单位设置各个位

时间:2013-04-02 13:02:21

标签: c bit-manipulation

例如:

We have a byte A: XXXX XXXX
We have a byte B: 0000 0110

现在我们想要特定位置的字节B中的4位,我们希望将字节A放在特定位置上,这样我们得到一个结果:

We have a byte A: 0110 XXXX

我仍在搜索魔术功能但没有成功。

发现类似并重新加工但仍然没有结束:

unsigned int i, j; // positions of bit sequences to swap
unsigned int n;    // number of consecutive bits in each sequence
unsigned int b;    // bits to swap reside in b
unsigned int r;    // bit-swapped result goes here

unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));
As an example of swapping ranges of bits suppose we have have b = 00101111 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would be r = 11100011 (binary).
This method of swapping is similar to the general purpose XOR swap trick, but intended for operating on individual bits.  The variable x stores the result of XORing the pairs of bit values we want to swap, and then the bits are set to the result of themselves XORed with x.  Of course, the result is undefined if the sequences overlap.

3 个答案:

答案 0 :(得分:0)

很难完全理解你的要求,所以如果我错了就纠正我:

你想取一个字节的最后4位(B)并将它们加到第一个字节A的位中?你使用“put inside”这个词,但不清楚你的意思是什么(如果没有添加,你的意思是替换吗?)。

因此,假设您想要添加,您可以执行以下操作:

A = A | (B <<4)

这将向左移4位(从而以01100000结束),然后将其“添加”到A(使用或)。

答案 1 :(得分:0)

  

字节A:YYYY XXXX

     

字节B:0000 0110

你想要0110 XXXX

所以AND A和00001111然后复制B的最后4位(第一次移位然后是OR)

a &= 0x0F; //now a is XXXX
a |= (b << 4); //shift B to 01100000 then OR to get your result

如果你想要0110 YYYY只需向右移动4而不是AND

a >>= 4

答案 2 :(得分:0)

找到解决方案:

x = ((b>>i)^(r>>j)) & ((1U << n) -1)
r = r^(x << j)

其中r是第二个BYTE,i,j是按顺序(从,到)的索引。