1

But I just don't know how compiler would know that I have passed binary number but not integer. . For ex I want to divide 10010(binary format) and 1110(binary format) how to do it??

Dominique
  • 16,450
  • 15
  • 56
  • 112
Anuj
  • 21
  • 4
  • Which programming language is this? – Dominique Sep 20 '18 at 07:25
  • It's a Java programming language. – Anuj Sep 20 '18 at 07:28
  • I've edited your question and added the tag. There are quite some users who are following those tags, so like this you might get help in a faster way. – Dominique Sep 20 '18 at 07:29
  • https://stackoverflow.com/questions/7971074/working-with-binary-numbers-in-java This may help. – Echo Sep 20 '18 at 07:45
  • Unfortunately, your question is unclear. Java's type system does not include "binary number" and therefore there is no such thing as "divide 10010(binary format) and 1110(binary format)". Java's type system includes integer, long, float, double and the arithmetic operation of division is available only on those. If you have whatever textual representation of a number (that happens to be "binary format") then first convert that representation to a value of the java type system and then do the division. – Erwin Smout Sep 20 '18 at 09:19

2 Answers2

1

To take this input from a scanner you can use Integer.parseInt(String, radix) function.

You would then minus one int from the other and convert the result back into a binary String to display it.

import java.util.Scanner;

public class Main3 {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int one = Integer.parseInt(scan.nextLine(),2);
        int two = Integer.parseInt(scan.nextLine(),2);
        String result = Integer.toBinaryString(one - two);
        System.out.println(result);
    }
}
  • Thank you this worked. But instead minus I had to divide so division operator would come there. – Anuj Sep 23 '18 at 20:17
0

Since Java 7 you can use binary literals adding the prefix 0b to the number.

int anInt1 = 0b10010;

https://docs.oracle.com/javase/8/docs/technotes/guides/language/binary-literals.html

javaleryon
  • 76
  • 2