5

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

3
  • 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" Commented Mar 19, 2015 at 8:21
  • 1
    @fge but it is called ones complement. Commented 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. Commented May 3, 2016 at 21:39

3 Answers 3

11
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
Sign up to request clarification or add additional context in comments.

1 Comment

Simplest answer ever found for complementing any operator!
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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.