In  this tutorial, we will see “How to convert Hexadecimal to Binary using Java 8?”

How to convert hexadecimal number to Binary in java

Java 8 – How to convert Hexadecimal Number to Binary? Share on X

/**
 * Using Java8, Convert Hexadecimal Number to Binary
 * @author Deepak Verma
 *
 */

import java.util.stream.IntStream;

public class Convert_Hexadecimal_to_Binary_Java8_Example {

	public static String hexadecimalToBinary(String hexadecimalNumber) {
	    
		return IntStream.range(0, hexadecimalNumber.length())
	                    .mapToObj(i -> Integer.toBinaryString(Character.digit(hexadecimalNumber.charAt(i), 16)))
	                    .map(x -> String.format("%4s", x).replace(" ", "0"))
	                    .reduce((x1, x2) -> x1 + x2)
	                    .get();
	  }

	  public static void main(String[] args) {
	    String hexadecimalNumber = "FF";
	    String binaryValue = hexadecimalToBinary(hexadecimalNumber);
	    System.out.println("Binary counterpart of " + hexadecimalNumber + ": " + binaryValue);
	  }
}

 

Output:

Binary counterpart of FF: 11111111

How to convert hexadecimal number to Binary in java

In above example, It uses the IntStream class of Java 8 java.util.stream package to convert each character in the hexadecimal string to its binary counterpart. The mapToObj method is used to map each integer to a binary string using the Integer.toBinaryString method. Then, the map method formats each binary string to have four digits by padding it with zeros if necessary. At last, the reduce method joins all the binary strings into one string.

How to convert hexadecimal number to Binary in java

Java 8 – How to convert Hexadecimal Number to Binary? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts