Why ~1 returns -2 rather than 0 in Java?

107 views Asked by At

I'm trying to negate(a.k.a invert) all bits of given int.

Lets say the given number's(given number is 5) binary representation is 101, and its negation (my output) should be 010.

I'm using ~ for each and every bit from least significant bit to most significant bit, to negate it.

public static void main (String[] args) throws java.lang.Exception
    {
        // your code go
        int num = 5;
        String givenNumInBinary = Integer.toBinaryString(num);
        StringBuffer output = new StringBuffer();

        for(int i = 0; i <= givenNumInBinary.length()-1;i++){
            int msb = Character.getNumericValue(givenNumInBinary.charAt(i));
            output.append(~msb);
        } 
        System.out.println(output.toString());
    }

My output turns out to be -2-1-2

Why is that? What am I doing wrong?

1

There are 1 answers

3
Scary Wombat On BEST ANSWER

Because you are inversing each digit at

int msb = Character.getNumericValue(givenNumInBinary.charAt(i));
output.append(~msb);

rather than inversing each bit.

Alternate solution would be

output.append(msb == 0 ? 1 : 0);
....
System.out.println(output.toString());

output

010