1's complement to 2's complement conversion

3.7k views Asked by At

My code is a class for converting decimal to binary. it will display the binary, one's complement and two's complement. So far I have figured out the one's complement but having a problem finding a solution for the two's complement. my plan was to use the output of the ones complement as an input to the two's complement method and convert there. Is this the right approach?

//This method will convert binary result to ones complement
public String do1sComp(){
    if (binaryValue.length() == 0)
        doBinary();

    //Ones Complement
    char[] digits = binaryValue.toCharArray();
    for (char digit : digits){
        if(digit == '0'){
            onesComp += "1";
        }
        else 
            onesComp += "0";
        }

    return onesComp;
}

/* This was my attempt to start the method
public String do2sComp(){
    if (onesComp.length() == 0){
        if (binaryValue.length() == 0)
            doBinary();

        do1sComp();
    }

    //Twos Complement


} */
}
1

There are 1 answers

5
An SO User On BEST ANSWER

2's complement is just adding a 1 to the 1's complement. Now, you are adding a binary bit 1 and not an int 1.

You will be storing the 2's complement in an int. Just add another int that contains binary 1. Getting two's complement is a little bit more involved. This involves bitwise addition. However, there is a trick to it that I had learned in highschool.

Consider the number six in binary as 0110. The one's complement is 1001. The two's complement is 1010. The trick is this, find the right-most one. Having done that, flip the bits to the left of it, all the way to the end.

Use Integer.toBinaryString() to see your answer.

To store a bit 1 in an int, you'd do int bit = 0b0001 This will store a bit 1 in the lower-order bits of the int.

PS: I haven't made an SSCCE. Please correct me if I am wrong