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!
Asked
Active
Viewed 79 times
-2
-
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 Answers
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
-
1the mask (`0xf`) could probably be dynamically computed using `(Integer.highestOneBit(x) << 1) - 1` – Lino Apr 19 '21 at 07:54
-
1Well yea ... but the OP is "specifying by example", and Eran's solution meets the specification :-) – Stephen C Apr 19 '21 at 07:55
-
1