Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 547
MananMehta Avatar asked Mar 19 '15 08:03

MananMehta


2 Answers

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
like image 176
Eran Avatar answered Sep 18 '22 03:09

Eran


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

like image 41
Himanshu Goel Avatar answered Sep 21 '22 03:09

Himanshu Goel