【问题标题】:Perform binary addition and subtraction with a signed binary numbers in Java在 Java 中使用带符号的二进制数执行二进制加法和减法
【发布时间】:2016-02-08 02:53:18
【问题描述】:

为了纯粹的享受,在我的时间里,我正在尝试更多地了解二进制数和汇编。我去过当地图书馆借阅了一些书籍,以便对二进制数和加法有更多的了解。几周前我什至不知道,可以用 Java 添加二进制数。我被绊倒了,已经在这上面呆了两天。

就像我说的那样,我正在尝试将二进制数加上加法和减法。我假设我需要解析所有内容才能使其正常工作。我觉得我在这里看多了。究竟缺少什么?任何帮助都会有所帮助。

截至目前,我有这个:

`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);
        }
    }

【问题讨论】:

  • 注意:你的减法是以 4 为底,而不是以 2 为底。

标签: java binary


【解决方案1】:

toBinaryString 始终打印为 32 位无符号值。你需要一个类似的方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 2013-10-03
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多