Anuj
Anuj

Reputation: 21

I want to divide two binary numbers in Java

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??

Upvotes: 1

Views: 1507

Answers (2)

Hakanoreaver
Hakanoreaver

Reputation: 59

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

Upvotes: 1

javaleryon
javaleryon

Reputation: 76

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

Upvotes: 0

Related Questions