[英]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 位表示的補碼),該怎么辦?
您可以按位 AND ~nm
使用在所有位 <= nm
的最高 1 位中具有 1 位的數字。 在5
的情況下,您必須與0b111
按位與。
通常,您可以按如下方式計算掩碼:
System.out.println (Integer.toBinaryString ((-1 >>> Integer.numberOfLeadingZeros (nm)) & ~nm));
這將打印10
,而不是您想要的010
,因為省略了前導0
。
解釋:
當nm == 5
, Integer.numberOfLeadingZeros (nm)
將返回29
,因此-1 >>> 29
將返回0b00000..0111
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.