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.

3
  • 1
    The error is ocurring on which line? Also... Do you really need to parseInt product? Commented Apr 20, 2020 at 21:52
  • 1
    like this one stackoverflow.com/questions/2406432/… Commented Apr 20, 2020 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); Commented Apr 20, 2020 at 22:26

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.