简体   繁体   中英

Binary Ones Complement Operator in Java

Why and how does System.out.println(~4); gives output -5 and System.out.println(~0); gives output -1 ?

4 is  00000000 00000000 00000000 00000100

~4 is 11111111 11111111 11111111 11111011 = -5

0 is  00000000 00000000 00000000 00000000

~0 is 11111111 11111111 11111111 11111111 = -1

negation of a number reverses it's bits. But on putting -(negative) sign on number logically it becomes 1+(~x) .

Since -x = 1+(~x) thus (~x) = -x -1

And if you are wondering why

11111111 11111111 11111111 11111011 = -5

you could read more about two's complement and negative numbers:

two's complement

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