簡體   English   中英

如何獲得所需位數的 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
  • 第 1 行給出 --> 101
  • 第 2 行給出 --> 111111111111111111111111111111 010

我知道第 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 == 5Integer.numberOfLeadingZeros (nm)將返回29 ,因此-1 >>> 29將返回0b00000..0111

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM