Why and how does System.out.println(~4); gives output -5 and System.out.println(~0); gives output -1 ?
-
Integers in java use two's completement, not one's complement, and the operator you are using is called bitwise negation, not "binary one complement"fge– fge2015-03-19 08:21:15 +00:00Commented Mar 19, 2015 at 8:21
-
1@fge but it is called ones complement.user555045– user5550452015-03-19 09:49:45 +00:00Commented Mar 19, 2015 at 9:49
-
That's right @harold. Ones complement is the most common term, followed by "bitwise NOT". I've never heard the term "bitwise negation" before. Although I see that term is also legit, it's scarily close to "negation" which in fact is 2s complement, and not what the OP is asking about. I'd avoid using that term due to potential confusion.BobDoolittle– BobDoolittle2016-05-03 21:39:55 +00:00Commented May 3, 2016 at 21:39
Add a comment
|
3 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
1 Comment
Apurva
Simplest answer ever found for complementing any operator!
And if you are wondering why
11111111 11111111 11111111 11111011 = -5
you could read more about two's complement and negative numbers: