2

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


} */
}
Martin Thorsen Ranang
  • 2,394
  • 1
  • 28
  • 43
tms777
  • 35
  • 1
  • 5
  • 2
    To get the 2's complement, take the 1's complement and add one. – Hot Licks Jan 19 '14 at 04:38
  • Where would I add the 1? – tms777 Jan 19 '14 at 04:41
  • You'd add it to the low-order bit, then ripple-carry up the line as required. Just like you'd add 1 to any number. – Hot Licks Jan 19 '14 at 04:46
  • Initial number `01010100`, 1's complement `10101011`. Add 1 = `10101100`. (An interesting attribute of a binary number and it's 2's complement is that both will have the same number of right-hand zeros.) – Hot Licks Jan 19 '14 at 04:49
  • (And you can isolate the least-significant 1 in a binary number by ANDing the number with it's 2's complement.) – Hot Licks Jan 19 '14 at 04:50
  • @tms777: You're aware `Integer.toBinaryString` exists, right? – blackcompe Jan 19 '14 at 04:52
  • I'm new to programming. Not familiar with that but am interested in how it can be implemented. Been looking it over and it seems to be what I looking for, just need a little help getting it going. – tms777 Jan 19 '14 at 05:04

1 Answers1

4

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

An SO User
  • 24,612
  • 35
  • 133
  • 221