-1

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?

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
sofs1
  • 3,834
  • 11
  • 51
  • 89
  • @TimBiegeleisen Done. – sofs1 Oct 15 '18 at 02:12
  • If the duplicate link still leaves you wondering, then try [reading this good tutorial](https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html) from the Cornell CS department. Basically, you just need to figure out how 2's compliment works. – Tim Biegeleisen Oct 15 '18 at 02:24
  • @TimBiegeleisen I read both the answer and the article. I still don't get it. My question is simple. `5` in two's complement is `101`. Negating each bit should be `010`. Why am I getting `-2-1-2`?? – sofs1 Oct 15 '18 at 02:32
  • Because you're negating each digit _individually_. Maybe the @wombat answer below is what you intended to do, but were not actually doing. – Tim Biegeleisen Oct 15 '18 at 02:33
  • @TimBiegeleisen So, What is the negate table in binary as similar to ^, & and | ? Here is the table for &, | and ^ https://imgur.com/a/V4w5JdG – sofs1 Oct 15 '18 at 02:35
  • An int is 32 bits so when you invert it, every one is altered. – Peter Lawrey Oct 15 '18 at 06:32

1 Answers1

1

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
sofs1
  • 3,834
  • 11
  • 51
  • 89
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • Thanks for answering. 5 in two's complement is 101. Negating each bit should be 010. Why am I getting -2-1-2 (That is my question). I'm not asking for an alternative solution. – sofs1 Oct 15 '18 at 02:32
  • 1
    because you are not inversing the bits you are inversing the digit 1 – Scary Wombat Oct 15 '18 at 02:35
  • There you go. You nailed it with the explanation. Thanks. – sofs1 Oct 15 '18 at 02:36