如何在C语言中翻转和反转一个整数?

4
例如:
输入:01011111
输出:00000101
我知道可以使用“~”来翻转一个数字,但我不知道如何好的反转它。而且我不确定它们是否可以一起完成。
有人有什么想法吗?

可能是C中无符号整数反转位的重复问题。 - Jacob
你知道如何为一个数组编写一个反转函数吗?这可以用类似的方式完成。 - Thomas Eding
1个回答

8

如果你需要这类的东西,我建议你去fantastic的位运算技巧网页查看。以下是该页面的解决方案之一:

Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division):

unsigned char b; // reverse this (8-bit) byte

b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;

The multiply operation creates five separate copies of the 8-bit byte pattern to fan-out into a 64-bit value. The AND operation selects the bits that are in the correct (reversed) positions, relative to each 10-bit groups of bits. The multiply and the AND operations copy the bits from the original byte so they each appear in only one of the 10-bit sets. The reversed positions of the bits from the original byte coincide with their relative positions within any 10-bit set. The last step, which involves modulus division by 2^10 - 1, has the effect of merging together each set of 10 bits (from positions 0-9, 10-19, 20-29, ...) in the 64-bit value. They do not overlap, so the addition steps underlying the modulus division behave like or operations.

This method was attributed to Rich Schroeppel in the Programming Hacks section of Beeler, M., Gosper, R. W., and Schroeppel, R. HAKMEM. MIT AI Memo 239, Feb. 29, 1972.

以下是一种不使用64位整数的反转字节中的位,只需要7个操作:

b = ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;

请确保将结果分配或转换为无符号字符,以删除高位中的垃圾。这个方法是由Sean Anderson于2001年7月13日设计的。Mike Keith在2002年1月3日发现了一个错误并进行了更正。

另外还有其他解决方案可供参考。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接