-2

I have a simple question, how do I get the twos compliment instead of the regular answer from binary? I have a program that does the booths algorithm but when it returns the decimal it gives me a number that's a bit too high, I'm doing 9 * -9 and the answer it gives is 65455. I just want to know if there is a way to get the twos compliment instead (-81). The binary I get from the code is 1111111110101111 which I know from looking around does equal -81 when finding the two's compliment, I just don't know how to get my program to recognize or say that.

Edit: I found a small fix, essentially just checking if the binary of the product equals the result I got, this is how I've been printing the binary and converting it to a decimal, putting in the print area as The answer said something had to be done here, I got it working properly but would like to clean it up if I can

public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the first number: ");
    int operand1 = sc.nextInt();
    System.out.print("Enter the second number: ");
    int operand2 = sc.nextInt();
    String answer = multiply(operand1, operand2);
    System.out.println("Final Product (binary): " + answer);
    int decimal=Integer.parseInt(answer,2); 
    if(operand1 * operand2 < 0) {
        int decProduct = operand1 * operand2;
        String biProduct = toBinary(decProduct, 16);
        if (biProduct.length() > 16) 
        {
            biProduct = biProduct.substring(biProduct.length() - 16);
        } 
        if(biProduct.equals(answer)) {
            decimal = decProduct;
        }
    }
    System.out.println("Final Answer (decimal): " + decimal);  
}
  • When you only have 16 bits you get to decide if one of the bits is a plus/minus sign leaving 15 bits for the number or you define the number to be positive and have all 16 bits. Here you have a situation where you disagree with the JVM on which way to do it. – Thorbjørn Ravn Andersen Oct 28 '21 at 23:57

1 Answers1

1

The computer has no idea what it means. It just has some memory and in that memory are bits. The bits that are in it, are e.g. 1111111110101111.

What does that sequence mean? Who knows. The computer doesn't know or care.

It's the print code that decides. IT decides that this is to be taken in and then rendered such that the characters -, 8, and 1 appear on your computer screen.

Thus, the error here, is in the print code. There is no converting required. The bit sequence is all the things, at once: It's 1111111110101111, it's 65455, and it is -81. Which one is shown depends on how you print it.

Given that your print code isn't in the question, you're going to have to figure it out with this information.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72