[英]Java bitwise operator ^ - how do the bits shuffle
Here goes a small example.这是一个小例子。
int a = 11; //1 0 1 1 is bit representation
System.out.println(~a);
Output: -12
As I understand the '~' operator inverts the bits - ie 1 0 1 1 should now be 0 1 0 0 hence the output should have been 4. What am I missing?据我了解,'~' 运算符反转位 - 即 1 0 1 1 现在应该是 0 1 0 0 因此输出应该是 4。我错过了什么?
11
is not represented as 1011
, it is represented as: - 11
不表示为1011
,它表示为: -
0000 0000 0000 0000 0000 0000 0000 1011
It's just that you don't notice see the leading 0's
.只是您没有注意到看到前导
0's
。 Remember, int
s are of 32 bits.请记住,
int
是 32 位的。
Now , ~11
would be: -现在,
~11
将是:-
1111 1111 1111 1111 1111 1111 1111 0100
So, this is a negative number.所以,这是一个负数。 So, taking it's 2's complement and you get: -
所以,取它的 2 的补码,你会得到: -
0000 0000 0000 0000 0000 0000 0000 1011 // 1's complement
0000 0000 0000 0000 0000 0000 0000 1100 // 2's complement == -12
Hence, you get -12
.因此,你得到
-12
。
An int is many more digits than 4, it's actually got a bunch of 0's before what you put. int 比 4 多得多,它实际上在你输入之前有一堆 0。
Negative numbers on computers are usually represented as starting with ones.计算机上的负数通常表示为以 1 开头。 a -1 is generally all ones, -2 is ..11111111111111110, -3 is ..1111111111111101, etc.\\
a -1 一般为全 1,-2 为 ..11111111111111110,-3 为 ..1111111111111101,等等。\\
So what you got was a negative number because you changed all those zeros to ones.所以你得到的是一个负数,因为你把所有的零都改成了一。
If you want to see your number, use ~a & 0xf如果您想查看您的号码,请使用 ~a & 0xf
0xf will give you a "mask" of ...000001111 0xf 会给你一个 ...000001111 的“面具”
Anything anded with that will only retain the last 4 bits, all the rest will be zeroed out.与此相关的任何内容都将仅保留最后 4 位,其余所有将被清零。
GREAT question, glad to see people still experiment with / think of this stuff.好问题,很高兴看到人们仍在尝试/思考这些东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.