0

I am unable to understand how the following code gives -12. Please help me.

int a=11;    
int result=~a;    
System.out.println(result);    

I thought it will give 4. but yes I saw a preceding zero.
I guess it has got something to do with 2's complement but cant makes out how.

Hille
  • 2,123
  • 22
  • 39
pankaj
  • 11
  • 2's complement = (-x) - 1. Thus, this would be giving you -12. Please read this: https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python – Dhruv Aggarwal Dec 01 '17 at 07:14

1 Answers1

4

11's binary representation is 00000000000000000000000000001011.

The negation of that number is 11111111111111111111111111110100.

That's the 2's complement representation of -12.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • thank you Eran for quick response but how do i convert 0100 to -12 and how to know i have to do 2's complement? – pankaj Dec 01 '17 at 08:47
  • @pankaj A negative number is always represented in Java as 2' complement. When you negate a positive number, you'll get a negative number. The value of `11111111111111111111111111110100` is -12 since you have to add 1100 (12) to it to reach 2^32 (1 followed by 32 0s). Similarly `11111111111111111111111111111111` is `-1`, since you have to add 1 to it to reach 2^32. – Eran Dec 01 '17 at 08:54