0

例如:

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.
4

3 回答 3

0

找到了解决方案:

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

其中 r 是第 2 个字节,i,j 是按顺序排列的索引 (from,to)。

于 2013-04-02T14:12:53.843 回答
0

很难准确理解您的要求,如果我错了,请纠正我:

您想获取一个字节 (B) 的最后 4 位并将它们添加到第一个字节 A 的位吗?您使用“放入”一词,但不清楚您的确切含义(如果不添加,您的意思是替换吗?)。

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

A = A | (B <<4)

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

于 2013-04-02T13:11:58.130 回答
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 只需将 a 向右移动 4 而不是 AND

a >>= 4
于 2013-04-02T13:12:08.163 回答