Java : Convert Decimal to Binary


In this blog, you will learn to convert decimal number into binary string. The java.lang package provides api’s to convert a decimal number into a binary number.

Example
This program takes a decimal number from user as string and convert it to decimal number. toBinaryString() method takes an integer type value and returns its string representation of integer values which represents the data in binary. The base of binary number is 2.

import java.util.Scanner;

public class ConvertDecimalToBinary {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

System.out.println("Enter the decimal value:");
String hex = scan.nextLine();
// convert String to Int
int i = Integer.parseInt(hex);
// convert integer to binary
String by = Integer.toBinaryString(i);
// print binary String
System.out.println("Binary: " + by);
}
}

Output


Enter the decimal value:
12
Binary: 1100

Enter the decimal value:
200
Binary: 11001000
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s