简体   繁体   中英

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?

11 is not represented as 1011 , it is represented as: -

0000 0000 0000 0000 0000 0000 0000 1011

It's just that you don't notice see the leading 0's . Remember, int s are of 32 bits.

Now , ~11 would be: -

1111 1111 1111 1111 1111 1111 1111 0100

So, this is a negative number. So, taking it's 2's complement and you get: -

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 .

An int is many more digits than 4, it's actually got a bunch of 0's before what you put.

Negative numbers on computers are usually represented as starting with ones. a -1 is generally all ones, -2 is ..11111111111111110, -3 is ..1111111111111101, etc.\\

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

0xf will give you a "mask" of ...000001111

Anything anded with that will only retain the last 4 bits, all the rest will be zeroed out.

GREAT question, glad to see people still experiment with / think of this stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM