如何获得所需位数的 1 的补码,而不是获得 java 中数字的所有 32 位表示的补码?

How to get the 1's complement of just necessary number of bits, rather than getting complement of all 32 bits representation of the number in java?

int nm = 5;
System.out.println(Integer.toBinaryString(nm));   // line 1
System.out.println(Integer.toBinaryString(~nm));  // line 2

我知道第2行输出的原因

如果我只希望第2行输出010(只是5(101)的补码,而不是5的32位表示的补码)怎么办?

您可以按位与 ~nm 与一个在所有位中都有 1 位的数字 <= nm 的最高 1 位。在 5 的情况下,您必须按位与 0b111.

一般来说,您可以按如下方式计算掩码:

System.out.println (Integer.toBinaryString ((-1 >>> Integer.numberOfLeadingZeros (nm)) & ~nm));

这将打印 10,而不是您想要的 010,因为前导 0 被省略了。

解释:

nm == 5

Integer.numberOfLeadingZeros (nm) 将 return 29,因此 -1 >>> 29 将 return 0b00000..0111.