0
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

    String a = "10";
    String b = "11";

    int a0 = Integer.parseInt(a, 2);
    int b1 = Integer.parseInt(b, 2);

    int product = a0 * b1;
    Integer.toString(product);
    int result = Integer.parseInt(product);
    System.out.print(result);
    }
}

I've tried all the methods I've seen in stackoverflow and none of them work in my case. I can convert the binary to base10, but can't convert it back.

mone-
  • 13
  • 2
  • 1
    The error is ocurring on which line? Also... Do you really need to parseInt product? – marcellorvalle Apr 20 '20 at 21:52
  • 1
    like this one https://stackoverflow.com/questions/2406432/converting-an-int-to-a-binary-string-representation-in-java – Ryuzaki L Apr 20 '20 at 21:52
  • Printed binary is simply a visual representation of a number like decimal, or hex. But the default when printing integers is to print them in the decimal representation. If you want a binary string, just do `String result = Integer.toBinaryString(product);` – WJS Apr 20 '20 at 22:26

1 Answers1

3

Internally, everything is binary. But visually, binary is just one representation for human consumption. Other primary ones are octal, decimal, or hex. But the default when printing integers is to print them in the decimal representation. If you want a binary string, just do:

    String a = "10";
    String b = "11";

    int a0 = Integer.parseInt(a, 2);
    int b1 = Integer.parseInt(b, 2);

    int product = a0 * b1;
    String result = Integer.toBinaryString(product);
    System.out.print(result);

Prints

110

Also note that you can assign ints a value in binary representation.

int a = 0b11;
int b = 0b10;
WJS
  • 36,363
  • 4
  • 24
  • 39