Explain how Bitwise negation (~) works for an integer number? And why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Explain how Bitwise negation (~) works for an integer number? And why?

6th Jan 2017, 3:02 AM
Deep chand
Deep chand - avatar
2 Answers
+ 2
This is going to be complex, so put your thinking cap on. Let's take a relatively small number - I'll go with 114. If you only use one unsigned byte to represent that, 114 in decimal is the same as 01110010 in binary. So if you perform a bitwise negation on that, every 1 turns into a 0 and every 0 turns into a 1. So ~01110010 is equal to 10001101 (or 141 in decimal). Like I said, though, this particular byte is unsigned. If it is signed, it gets weird. In Java, the numbers are signed by default. So the bit that defines whether or not the byte contains a negative number is the one furthest to the left. In the following examples, I'll enclose that particular bit in parentheses (). So (0)1110010 is a positive number, while (1)0001101 is negative. The number (1)0000000 is equal to -128, and the digits count up from there - so (1)0000001 is equal to -127, and so on. So (0)1110010, or 114, becomes (1)0001101 when negated, or -113. That was complicated, wasn't it? Don't worry about it. There's not much reason to actually use bitwise negation on an integer, and I don't blame you if this made your head spin.
6th Jan 2017, 4:53 AM
DaemonThread
DaemonThread - avatar
+ 1
@Sean Curry Whenever I apply negation(~) to a number, it adds one to it and a sub(-). Example : ~69= -70. ~1=-2. ~13= -14. Why?
6th Jan 2017, 12:47 PM
Deep chand
Deep chand - avatar