Positive negation in Java

96 Views Asked by At

How to make that after the negation operation, i.e. ~ 10 (binary: 1010), the result would not be -11 but 5, 10 = binary 1010 and after negation 0101 or 5. Thank you for help!

1

There are 1 best solutions below

3
On BEST ANSWER

The binary representation of 10 is not 1010, it's 000...0001010 (with total of 32 bits).

Therefore the negation is 111...1110101, which is -11.

If you want to get 5, you need to keep only the least significant 4 bits (and reset all the rest to 0):

int x = 10;
System.out.println (~x & 0xf);

For a more general solution, if you want to negate only the n least significant bits (where n-1 is the index of the highest 1 bit in the input number) and keep all the higher bits 0, you can use Lino's suggestion:

System.out.println (~x & ((Integer.highestOneBit(x) << 1) - 1));