-2

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!

Vladik
  • 9
  • 1
  • You are mistaken, `~` is not a "negation operation". Java has the [`-` (Unary Minus Operator)](https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.15.4), which performs a negation of numeric values, as well as the [`~` (Bitwise Complement Operator)](https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.15.5) and the [`!` (Logical Complement Operator)](https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.15.6), neither of which does "negation". – Andreas Apr 19 '21 at 08:08

1 Answers1

2

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));
Eran
  • 387,369
  • 54
  • 702
  • 768