~运算符在Java中如何工作?

huangapple go评论81阅读模式
英文:

How does ~ operator works in Java?

问题

我在查找Java中的一些位运算,并找到了 ~ 运算符。
我找到了以下解释:

> ~a 的结果来自于 a,通过反转 a 的所有位。

因此,当我执行 System.out.println(~1) 时,为什么输出是 -2?
因为 0001 = 1,在取反后应该是 1110。

英文:

I was looking for some bit-Operations in Java and found the ~ operator.
I found following explenation:

> ~a results from a, by inverting all bits of a

So when I make a System.out.println(~1), why is the output -2?
As 0001 = 1 after inverting it should be 1110

答案1

得分: 2

只需要记住负数是以补码表示的。这意味着你首先要对这个数取补码,然后再加1。

int val = 20;
val = (~val)+1;
//  20     ==   0b00000000000000000000000000010100
// ~20     ==   0b11111111111111111111111111101011
// (~20)+1 ==   0b11111111111111111111111111101100 
System.out.println(val);

输出

-20

无论值是整数还是浮点数,最高位都是符号位。1表示负数,0表示非负数。

英文:

Just remember that negative numbers are stored in two's complement representation. So that means you first take the complement of the number and then add 1.

int val = 20;
val = (~val)+1;
//  20     ==   0b00000000000000000000000000010100
// ~20     ==   0b11111111111111111111111111101011
// (~20)+1 ==   0b11111111111111111111111111101100 
System.out.println(val);

Prints

-20

And whether the value is an integer or floating point, the high order bit is the sign bit. 1 means negative, 0 means not negative.

huangapple
  • 本文由 发表于 2020年8月27日 20:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63615940.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定