简体   繁体   English

在Java中使用带符号的二进制数执行二进制加法和减法

[英]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. 几周前我什至不知道,有人可以用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. toBinaryString始终打印为32位无符号值。 You need a method like. 您需要类似的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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