This article is a simple Java program that converts the decimal number to binary, octal, and hexadecimal format. When it first came into my mind I thought I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two ways of converting decimal to binary etc I was simply amazed. It’s indeed extremely easy to do this in java and you can also write this program or use it is.
Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!
Converting decimal to binary in Java Example
Java has many ways to change the number system of a particular number, you can convert any decimal number into either binary system, hexadecimal system or octal system by following the same procedure. here is a code example of converting any decimal number into binary number in Java.
//decimal to binary
String binaryString = Integer.toBinaryString(number);
System.out.println("decimal to binary: " + binaryString);
//decimal to octal
String octalString = Integer.toOctalString(number);
System.out.println("decimal to octal: " + octalString);
//decimal to hexadecimal
String hexString = Integer.toHexString(number);
System.out.println("decimal to hexadecimal: " + hexString);
//second way
binaryString = Integer.toString(number,2);
System.out.println("decimal to binary using Integer.toString: " + binaryString);
//decimal to octal
octalString = Integer.toString(number,8);
System.out.println("decimal to octal using Integer.toString: " + octalString);
//decimal to hexadecimal
hexString = Integer.toString(number,16);
System.out.println("decimal to hexadecimal using Integer.toString: " + hexString);
A nice and little tip to convert decimal to binary or decimal to Octal, hex. This comes very handy many times when we want to do a quick conversion.
Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!
Related Java Tutorials
3 comments :
In Java java.lang package give us this conversion capability.
JAVA : Conversion Between Binary, Octal, Decimal and Hexadecimal
I was looking for Java program to convert decimal to binary, because its my homework assignment :) your Sample program and explanation helps a lot dude.Please keep writing these simple Java programs.
Me too, I also got homework to write a Java program which converts Decimal number to binary and Hexadecimal. Thank you for this nice and simple Java program tutorial.
Post a Comment