How bitwise compliment operator(~)is work with negative numbers...? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 11

How bitwise compliment operator(~)is work with negative numbers...?

https://code.sololearn.com/cPeZpiNsv21O/?ref=app

7th Apr 2020, 2:47 PM
NavyaSri
NavyaSri - avatar
4 Answers
+ 3
Lets assume that int is 1 byte. for: int a = 10; 0 000 1010 = a in binary When you apply NOT operator It flips all the bits. 1 111 0101 is now equal to a. Since you declared a as signed the first bit will be defining the sign, 0 for +; 1 for - sign. And, since twos complement is used to represent negative numbers in binary we are going to be finding the number like this: When the first bit is 1, meaning negative, think 1s as zero; 0s as one (except the first bit). Then find the number and add 1. Lets do it together: 1 111 0101 we will think 1s zero, zeros as 1. (First bit stays there) 1 000 1010, so this equals 10. You add 1, then you get 11. Then you put negative sign. So you get -11.
7th Apr 2020, 2:56 PM
Mustafa K.
Mustafa K. - avatar
+ 2
Yeah, i understand till now.what am I asked,.....compliment with negative number....means .... int b=-10; System.out.println(~b);//how it is work....
7th Apr 2020, 3:13 PM
NavyaSri
NavyaSri - avatar
+ 2
Okay then lets take a look at it. b = -10 1 000 0000 lets sculp this. Since we will be adding 1 to the result we need to get 9 here how do we get 9 ? 2^3 + 2^0 = 1 000 1001 (we were thinking 1s as zero, 0s as one.) So 1 111 0110 is the binary representation of -10. So lets apply NOT operator. 0 000 1001. What we get? Its 9.
7th Apr 2020, 3:23 PM
Mustafa K.
Mustafa K. - avatar
+ 1
I don't get it. It was just to visualize the representation. I mean, I used it as template to think while typing.
7th Apr 2020, 4:17 PM
Mustafa K.
Mustafa K. - avatar