如何获得1';在java中,是不是只得到所需位数的补码,而不是得到表示该位数的所有32位的补码? 第1行给出-->101 第2行给出-->11111111111111111 010

如何获得1';在java中,是不是只得到所需位数的补码,而不是得到表示该位数的所有32位的补码? 第1行给出-->101 第2行给出-->11111111111111111 010,java,bit-manipulation,Java,Bit Manipulation,我知道第2行输出的原因 如果我只希望第2行输出为010(只是5(101)的补码,而不是5的32位表示的补码),该怎么办?您可以按位执行,并且~nm使用所有位中有1位的数字>>29将返回0b00000..0111 int nm = 5; System.out.println(Integer.toBinaryString(nm)); // line 1 System.out.println(Integer.toBinaryString(~nm)); // line 2 System.out.

我知道第2行输出的原因


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

您可以按位执行,并且
~nm
使用所有位中有1位的数字>>29将返回
0b00000..0111

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