英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论