简体   繁体   中英

Multiplication of two Binary Numbers given as Strings

so I have a code that should multiplicate two Binary Numbers as String without using ParseInt. My code actually works by far but it's multiplicating as decimal numbers. Something in the part where it should do the addition is wrong. Thanks for any kind of help!

public static String multiply(String binary1, String binary2) 

    String b1 = new StringBuilder(binary1).reverse().toString();
    String b2 = new StringBuilder(binary2).reverse().toString();

    int[] m = new int[binary1.length()+binary2.length()];

    for (int i = 0; i < binary1.length(); i++) {
        for (int j = 0; j < binary2.length(); j++) {
            m[i+j] += (b1.charAt(i)-'0')*(b2.charAt(j)-'0');
        }
    }

    StringBuilder sb = new StringBuilder();

    for(int i=0; i < m.length; i++) {
        int mod = m[i]%10;
        int carry = m[i]/10;
        if (i+1 < m.length) {
            m[i + 1] = m[i + 1] + carry;
        }
        sb.insert(0, mod);

    }
    // delete leading zeros
    while (sb.charAt(0) == '0' && sb.length() > 1) {
        sb.deleteCharAt(0);
    }
    return sb.toString();
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("1. Faktor:  ");
    String input1 = scan.next("(0|1)*");
    System.out.print("2. Faktor:  ");
    String input2 = scan.next("(0|1)*");
    scan.close();
    System.out.println("Ergebnis: " + multiply(input1, input2));
}

}

You may not use Integer.parseInt but nobody forbid you to implement your own parser:

private static int parseBinaryString(String s) {
    int binary = 0;
    for (int i = s.length() - 1, c; i >= 0; i--) {
        binary <<= 1;
        c = s.charAt(i);
        if (c == '1') {
            binary++;
        } else if (c != '0') {
            throw new NumberFormatException(s);
        }
    }
    return binary;
}

Which can then be simply used like this in your multiply method:

private static String multiply(String a, String b) {
    return Integer.toBinaryString(parseBinaryString(a) * parseBinaryString(b));
}

And if you can't use Integer.toBinaryString you can implement that method yourself:

private static String toBinaryString(int i) {
    StringBuilder binary = new StringBuilder();
    for (int t = i; t != 0; t >>= 1) {
        binary.append((i & t) != 0 ? 1 : 0);
    }
    return binary.toString();
}

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