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:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: