int java.lang.Integer.reverse(int i)
Returns the value obtained by reversing the order of the bits in the two’s complement binary representation of the specified int value.
Parameters:
i
Returns:
the value obtained by reversing order of the bits in the specified int value.
Since:
1.5
源码:
注释部分参考了:https://blog.csdn.net/yinlinneverg/article/details/80918788
public static int reverse(int i) {
/**
* 以八位为例,表示为ABCDEFGH,其做法为:
* (1)每一位视为一个个体,每两位为一组进行反转,得到BADCFEHG
* (2)每两位视为一个个体,每四位为一组进行反转,得到DCBAHGFE
* (3)每四位视为一个个体,每八位为一组进行反转,得到HGFEDCBA
* 32位整数依次类推。
*/
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
/**
* 到这里为止,每八位之间的反转已经完成,使用字母代表八位的话,
* 现在该整数看做ABCD,接下来的操作就是将其反转为DCBA。(这个就代表了32位。)
* (1)i<<24实际上就是将D移动到A的位置,得到D000(每个0代表8个0)。
* (2)i&0xff00实际上是得到00C0,左移8位,将C移动到B的位置,得到0C00。
* (3)i>>>8实际上是将B移动到C的位置,得到0ABC,再和0xff00进行相与,得到00B0。
* (4)i>>>24实际上就是将A移动到D的位置,得到000A。
* (5)将上述四步得到的四个值进行相与,即可得到DCBA。
*/
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
0x为十六进制的前缀标识
0xaaaaaaaa = 10101010101010101010101010101010 (偶数位为1,奇数位为0)
0x55555555 = 01010101010101010101010101010101 (偶数位为0,奇数位为1)
0x33333333 = 00110011001100110011001100110011 (1和0每隔两位交替出现)
0xcccccccc = 11001100110011001100110011001100 (0和1每隔两位交替出现)
0x0f0f0f0f = 00001111000011110000111100001111 (1和0每隔四位交替出现)
0xf0f0f0f0 = 11110000111100001111000011110000 (0和1每隔四位交替出现)
((x & 0x55555555) << 1 — 奇数位移到偶数位
((x >> 1) & 0x55555555); — 先右移一位,等于拿到奇数位