不使用循环反向整数位元整数、位元

2023-09-11 04:23:56 作者:华丽外表

我想编写一个程序,它反转一个整数位。 防爆11000101到10100011 我知道如何使用一个循环来解决这个问题,但我碰到的使用字节偏移做IT解决方案:

I want to write a program which reverses the bits of an integer. Ex 11000101 to 10100011 I know how to solve this using a loop, but I came across solutions that do it using byte shift:

num>>4|num<<4

我不明白怎么做这项工作。有人可以HEP我呢?

I don't understand how does this work. Can somebody hep me with this?

推荐答案

这不是颠倒位,它的交换的半字节(4位)。换句话说,它会变成:

That's not reversing the bits, it's swapping the nybbles (4-bit units). In other words, it will turn:

1100 0101 (abcd efgh)

0101 1100 (efgh abcd)

和它这样做只是如果数据类型实际上是8位(否则 NUM&LT; 4; 地的一些位的八个最右边的人留下一个更安全。这样做是为了确保所有其他位前移位清零:

and it will do so only if the data type is actually 8 bits (otherwise num << 4 places some bits left of the eight rightmost ones. A safer way to do it is to ensure all other bits are cleared before shifting:

((num & 0xf0) >> 4) | ((num & 0x0f) << 4)

有关如何按位运算符工作preCIS,请参见这个优秀的答案。

For a precis on how bitwise operators work, see this excellent answer.

等效EX pression全额位反转, hgfe DCBA ,是相当可怕的:

The equivalent expression for a full bit reversal, hgfe dcba, is the rather monstrous:

  ((num & 0x01) << 7)
| ((num & 0x02) << 5)
| ((num & 0x04) << 3)
| ((num & 0x08) << 1)
| ((num & 0x10) >> 1)
| ((num & 0x20) >> 3)
| ((num & 0x40) >> 5)
| ((num & 0x80) >> 7)

,其提取并移动各八位。

which extracts and shifts each of the eight bits.