# Convert between Binary, Octal, Hex and Decimal in Java

Let’s look at a few Java examples of conversions between decimal, binary, octal, and hexadecimal. All examples use native Java APIs without adding any more complexity.

## 1. Binary, Octal, or Hex -> Decimal

Use Integer.parseInt(String input, int radix) to convert from any type of number to an Integer.

``````String binary = "10101";
int decimal1 = Integer.parseInt(binary, 2);
System.out.println(binaryNumber + " in Base 10 : " + decimal1);

String octal = "456";
int decimal2 = Integer.parseInt(octal, 8);
System.out.println(octal + " in Base 10 : " + decimal2);

String hex = "ABCD";
int decimal3 = Integer.parseInt(hex, 16);
System.out.println(hex + " in Base 10 : " + decimal3);``````

The program output:

``````10101 in Base 10 : 21
456 in Base 10 : 302
ABCD in Base 10 : 43981``````

## 2. Decimal -> Binary, Octal, or Hex

### 2.1. Using Integer.toString(int input, int radix)

Use Integer.toString(int input, int radix) to convert from an Integer to any type of base number.

``````Integer decimal1 = 21;
String binary = Integer.toString(decimal1, 2);
System.out.println(decimal1 + " in Base 2 : " + binary);

Integer decimal2 = 302;
String octal = Integer.toString(decimal2, 8);
System.out.println(decimal2 + " in Base 8 : " + octal);

Integer decimal3 = 43981;
String hex = Integer.toString(decimal3, 16);
System.out.println(decimal2 + " in Base 16 : " + hex);``````

The program output:

``````21 in Base 2 : 10101
302 in Base 8 : 456
43981 in Base 16 : abcd``````

### 2.2. Using Integer.toXyzString(int input, int radix)

`Integer` class does provide lots of utility methods to be consumed directly. Check out them in Java doc.

• Integer.toBinaryString()
• Integer.toOctalString()
• Integer.toHexString()
``````Integer decimal1 = 21;
System.out.println(decimal1 + " in Base 2 : " + Integer.toBinaryString(decimal1));

Integer decimal2 = 302;
System.out.println(decimal2 + " in Base 8 : " + Integer.toOctalString(decimal2));

Integer decimal3 = 43981;
System.out.println(decimal3 + " in Base 16 : " + Integer.toHexString(decimal3));``````

The program output:

``````21 in Base 2 : 10101
302 in Base 8 : 456
43981 in Base 16 : abcd``````

Happy Learning !!

Subscribe
Notify of
Inline Feedbacks

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.