Open In App

Java Program to Convert Byte Array to Hex String

Improve
Improve
Like Article
Like
Save
Share
Report

Byte Array – A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0.

Hex String – A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0’s and 1’s. Eg: “245FC” is a hexadecimal string.

Problem Statement – Given a byte array, the task is to convert the Byte Array to Hex String

Example: 

Input : byteArray = { 9, 2, 14, 10 }
Output: 9 2 E A

Input : byteArray = { 7, 12, 13, 127 }
Output: 7 C D 7F

The conversion of a Byte Array to Hex String involves changing an array of byte datatype to its hexadecimal value in the form of a string. There are numerous approaches to do the same; a few of them are listed below.

Approaches:

  • Using Format() Method in Java
  • Using Bitwise Shift Operators
  • Using the predefined method in Integer/Long Class
  • Using Hexadecimal Representation of BigInteger in Java

Approach 1 –  Using Format() Method in Java

Java String Format() method can be used for the specified conversion. For this,

  1. Iterate through each byte in the array and calculate its hexadecimal equivalent.
  2. The string.format() is used to print the number of places of a hexadecimal value and store the value in a string.
  3. %02X is used to print add two spaced between two hexadecimal values(of a hexadecimal (X)).

Following is the implementation of the foregoing approach:

Java




// Java Program to convert byte
// array to hex string
 
// Approach 1 -  Using Format() Method in Java
 
import java.io.*;
 
public class GFG {
    public static void convertByteToHexadecimal(byte[] byteArray)
    {
        String hex = "";
 
        // Iterating through each byte in the array
        for (byte i : byteArray) {
            hex += String.format("%02X", i);
        }
 
        System.out.print(hex);
    }
 
    public static void main(String[] args)
    {
        byte[] byteArray = { 7, 12, 13, 127 };
        convertByteToHexadecimal(byteArray);
    }
}


Output

070C0D7F

Time Complexity: O(n)
Auxiliary Space: O(n)
 

Approach 2 – Using Bitwise Shift Operators

In the previous approach, if the byte array gets larger, the process becomes slow. A byte operation is used to convert the byte array to a hexadecimal value to increase efficiency.

Here “>>>” unsigned right shift operator is used. And, toCharArray() method converts the given string into a sequence of characters.

Following is the implementation of the foregoing approach –

Java




// Java program to convert byte
// array to hex string
 
// Approach 2 - Using Bitwise Shift Operators
 
import java.io.*;
 
public 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, 127 };
        convertByteToHexadecimal(bytes);
    }
}


Output

09020E7F

Approach 3 – Using the predefined method in Integer/Long Class

The Integer class has toHexString() method that converts an integer to its hexadecimal equivalent. We now need to convert the byte array into an integer (for 4-sized) or long (for 8-sized) and use this method (as this method is present in both of the classes, i.e., Integer and Long with the same name). For converting byte array to integer or long, we can use the wrap method of the ByteBuffer class.

Following is the implementation of the foregoing approach –

Java




// Java program to convert byte
// array to hex string
 
// Approach 3 - Using the predefined method
// in Integer/Long Class
 
import java.io.*;
// Importing packages to use wrap methods
// of ByteBuffer Class
import java.nio.*;
 
public class GFG {
    public static String toHexadecimal(byte[] bytes)
    {
        StringBuilder result = new StringBuilder();
 
        for (byte i : bytes) {
            int decimal = (int)i & 0XFF;
            String hex = Integer.toHexString(decimal);
 
            if (hex.length() % 2 == 1) {
                hex = "0" + hex;
            }
 
            result.append(hex);
        }
        return result.toString();
    }
 
    public static void main(String[] args)
    {
        byte[] byteArray = { 9, 2, 14, 127 };
        System.out.println(toHexadecimal(byteArray));
    }
}


Output

09020e7f

Approach 4 – Using Hexadecimal Representation of BigInteger in Java

Using the Hexadecimal Representation of BigInteger class in Java is quite an avoided way of converting byte array to hex string due to its slow speed. Here one can also observe that since we deal with numbers and not arbitrary byte strings, this may omit leading zeros in cases.

Following is the implementation of the foregoing approach –

Java




// Java program to convert byte
// array to hex string
 
// Approach 4 - Using Hexadecimal Representation
// of BigInteger in Java
 
import java.io.*;
// Importing the BigInteger class
import java.math.BigInteger;
 
public class GFG {
    public static void toHexString(byte[] byteArray)
    {
        // Printing the hexadecimal equivalent as string
        // representation from the BigInteger class.
        System.out.print(
            new BigInteger(1, byteArray).toString(16));
    }
 
    public static void main(String[] args)
    {
        byte[] byteArray = { 17, 2, 14, 127 };
        toHexString(byteArray);
    }
}


Output

11020e7f


Last Updated : 14 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads