In the problem given a byte array and the task is to convert the Byte Array to Hexadecimal value. A Java Byte Array is used to store byte data types only and the default value of each element is 0.
Example :
Input : byteArray = { 9, 2, 14, 10 } Output: 09020E0A Input : byteArray = { 7, 12, 13, 8 } Output: 070C0D08
Approach:
- Iterate through each byte in the array and convert it to a hexadecimal value.
- The string.format() is used to print the number of places of a hexadecimal value and store it in a string.
- %02X is used to print two places of a hexadecimal (X).
Below is the implementation of the above approach :
Java
// Java Program to convert byte // array to hexadecimal value import java.io.*; class GFG { public static void convertByteToHexadecimal( byte [] byteArray) { // Iterating through each byte in the array for ( byte i : byteArray) { String hex = String.format( "%02X" , i); System.out.print(hex); } } public static void main(String[] args) { byte [] byteArray = { 9 , 2 , 14 , 10 }; convertByteToHexadecimal(byteArray); } } |
09020E0A
Efficient Approach:
In the above approach if the byte array gets larger, then the process becomes slow so to increase the efficiency a byte operation is used to convert the byte array to a hexadecimal value.
Here “>>>” is the unsigned right shift operator. And, toCharArray() method converts the given string into a sequence of characters.
Below is the implementation of the above approach :
Java
// Java program to convert byte array to // hexadecimal array using byte operation import java.io.*; class GFG { public static void convertByteToHexadecimal( byte [] byteArray) { int len = byteArray.length; // storing the hexadecimal values char [] hexValues = "0123456789ABCDEF" .toCharArray(); char [] hexCharacter = new char [len * 2 ]; // using byte operation converting byte // array to hexadecimal value for ( int i = 0 ; i < len; i++) { int v = byteArray[i] & 0xFF ; hexCharacter[i * 2 ] = hexValues[v >>> 4 ]; hexCharacter[i * 2 + 1 ] = hexValues[v & 0x0F ]; } System.out.println(hexCharacter); } public static void main(String[] args) { byte [] bytes = { 9 , 2 , 14 , 10 }; convertByteToHexadecimal(bytes); } } |
09020E0A
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.