简体   繁体   中英

Perform binary addition and subtraction with a signed binary numbers in Java

For pure enjoyment and on my time, I'm trying to learn more about binary numbers and assembly. I have been to the local library checking out some books in order to gain more understanding of binary numbers and addition. I didn't even know before a few weeks back, one could add binary numbers with Java. I'm stumbled and have been for two days on this.

Like I said I'm trying to add binary numbers in addition and subtraction. I'm assuming I need to parse everything in order for it work properly. I feel I'm over looking something here. What exactly is missing? Any help is helpful.

As of right now, I have this:

`import java.util.Scanner;
public class binary operation {
public static void main(String[]args){
    Scanner keyboard = new Scanner(System.in);
    boolean keepGoing = true;
    String binary1, binary2;
    int num1, num2;

    System.out.println("Scenario: Choose (A)dd, (S)ubtract, (E)xit");
    char choice = keyboard.next().charAt(0);
    while(keepGoing){
        if (choice == 'A' || choice == 'a'){
            System.out.println("Enter 8-bit signed binary number: "); 
            binary1 = keyboard.next();
            System.out.println("Enter another binary number: ");
            binary2 = keyboard.next();
            num1 = Integer.parseInt(binary1, 2);
            num2 = Integer.parseInt(binary2, 2);
            int sum = num1 + num2;
            System.out.println(Integer.toBinaryString(sum));
        }
        else if(choice == 'S' || choice == 's'){
            System.out.println("Enter 8-bit signed binary number: ");
            binary1 = keyboard.next();
            System.out.println("Enter another binary number: ");
            binary2 = keyboard.next();
            num1 = Integer.parseInt(binary1, 4);
            num2 = Integer.parseInt(binary2, 4);
            int difference = num1 - num2;
            System.out.println(Integer.toBinaryString(difference));
        }
        else if(choice == 'E' || choice == 'e'){
            System.out.println("Thank you.");
            keepGoing = false;
            System.exit(0);
        }
        if(keepGoing){
            System.out.println("Choose (A)dd, (S)ubtract, (E)xit");
            choice = keyboard.next().charAt(0);
        }
    }

The toBinaryString always prints as a 32-bit unsigned value. You need a method like.

public static String toSignedBinary(int num) {
    return num < 0 ? "-" + Long.toBinaryString(-(long) num) : Integer.toBinaryString(num);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM