0

I just started learning programming in Java. I made a program which calculates the complement of an integer

package demo;

public class unaryOperators {
    public static void main(String[] args) {
        int numOne = 10;
        System.out.println(~numOne);
    }
}

The program runs without any errors but the output is not as expected! The output was -11 but as far as I know, Bitwise complement operator complements all the bits of the number.

10 in decimal is 1010

So, ~10 should be 0101 i.e. 5 in decimal!

I referred some articles but cannot find one which in simple for a novice like me to understand.

Thanks for your time!

Aryan Soni
  • 51
  • 8
  • 2
    [This answer](https://stackoverflow.com/a/42311432/1016514) explains it quite well, I think. – Hans Jun 03 '22 at 19:23
  • 2
    two key facts will be brought up by good answers: your variable has all of its component bits, even if you don't need them to store the current value, so when you invert the bits of a variable, the leading 0s that you weren't thinking about are still there, and will be flipped to 1s. 2's complement is how negative numbers are stored, and if the top bit is a 1, the number's negative. – Gus Jun 03 '22 at 19:27
  • @Gus At first, I had no idea about 2's Complement but then after reading for a while, now it's all clear! Thanks for explaining in short but in-depth! – Aryan Soni Jun 04 '22 at 09:57

2 Answers2

2

Java integers are stored in two's complement. Assuming (for simplicity) that we're storing data in one byte, 10 is

00001010

so ~10 is

11110101

If the leading bit of a two's complement number is 1, then the number is negative, and the exact value of that number is (the negative of) its complement plus one, hence -11. You can read the details of why this format is written the way it is in the linked Wikipedia page.

Silvio Mayolo
  • 41,871
  • 4
  • 57
  • 86
1

In Java an int is a 32-bit value. So when you are doing the complement of 10 (decimal) it is
0000 0000 0000 0000 0000 0000 0000 1010 (binary) not just a 4-bit 1010 (binary).

Therefore, the complement of the 32-bit value ~10 is
1111 1111 1111 1111 1111 1111 1111 0101 (binary) which is signed -11 (decimal) and the output you are getting.

If you are just working with 4-bit numbers, you simply could XOR the integer value with 0xF (hex) which is just 1111 (binary). The XOR with all 1's performs the complement of the integer.

int numOne = 10;
System.out.println(numOne ^ 0xF);

This would give you the correct output. Hope this helps!

lyannul
  • 11
  • 3