Convert Binary to Hexadecimal in Java

Topic

In this program, we will convert a binary number (a number with only 0s and 1s) into its equivalent hexadecimal value (which uses 0-9 and A-F). Hexadecimal is often used in memory addresses and color codes. Understanding this conversion will strengthen your number system knowledge and bitwise thinking in Java.

Examples

Example 1:

Input: 1010 (binary)
Output: A (hexadecimal)

Example 2:

Input: 11111111
Output: FF

Example 3 (Edge Case):

Input: 0
Output: 0

Interviewer Expectations

The interviewer wants to assess:

  • Your understanding of different number systems.
  • String manipulation or use of built-in conversion methods.
  • How well you handle input validation and formatting.

Approach

We can approach this problem in two common ways:

  1. Using built-in Java functions: Convert the binary string to decimal using Integer.parseInt(binary, 2), then convert to hexadecimal using Integer.toHexString(decimal).
  2. Manually converting binary to decimal and then to hexadecimal using custom logic (for more challenge).

Dry Run

Input: 1111

Step 1: Convert binary to decimal: 15
Step 2: Convert decimal to hexadecimal: F
Output: F

Java Program

public class BinaryToHex {
    public static void main(String[] args) {
        String binaryStr = "101010";
        int decimal = Integer.parseInt(binaryStr, 2);
        String hex = Integer.toHexString(decimal).toUpperCase();
        System.out.println("Binary: " + binaryStr);
        System.out.println("Hexadecimal: " + hex);
    }
}
Binary: 101010
Hexadecimal: 2A

Possible Followup Questions with Answers

Q1: How can you convert a binary number to hexadecimal without using built-in functions?

You would need to first convert the binary string to a decimal manually, then repeatedly divide the decimal by 16 and store remainders, mapping them to hex digits.

Q2: What happens if the input string contains characters other than 0 or 1?

Using Integer.parseInt(binaryStr, 2) will throw a NumberFormatException. Always validate input before converting.

Q3: How would you handle very large binary numbers?

You can use BigInteger to safely handle large binary inputs:

BigInteger binary = new BigInteger("110110101011101010101", 2);
String hex = binary.toString(16).toUpperCase();

Q4: Can you do the reverse — hexadecimal to binary?

Yes, convert hex to decimal using Integer.parseInt(hexStr, 16), then to binary with Integer.toBinaryString(decimal).


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...