Java Program to Convert Byte Array into Hexadecimal

Java Program to Convert Byte Array into Hexadecimal

What is Byte Array in Java ?

A byte array is a collection of bytes, often used to store binary data. It can be used to store data in memory, or to read and write data to a file or network stream. In programming languages such as C#, Java and Python, byte arrays are often used to store and manipulate binary data such as images, audio and video files.

What is Hexadecimal ?

Hexadecimal, also known as hex or base 16, is a numeral system that uses 16 symbols to represent numbers, 0-9 and A-F. Each digit in a hexadecimal number represents 4 bits of data, making it a convenient way to represent binary data in a more compact and human-readable form. For example, the hexadecimal number “FF” represents the binary number “11111111”. Hexadecimal is commonly used to represent the color codes in web development and to represent memory addresses in computer programming.

Ways to convert a byte array to hexadecimal in Java:

  • Using the BigInteger class and the format method of the String class.
  • Using the javax.xml.bind.DatatypeConverter.printHexBinary() method, it will return a string of hexadecimal digits representing the byte array.
  • Using a loop and a lookup table: This method involves creating a lookup table of hexadecimal digits and then iterating through the byte array, converting each byte to its hexadecimal representation using the lookup table.
  • Using the Apache commons library, this library have a class named Hex that have a method named encodeHexString() it can be used to convert a byte array to its hexadecimal representation
  • Using the Guava library, Guava also have a method to convert byte array to hexadecimal representation,

Example 1 :

Run
import java.math.BigInteger;

public class Main {
    public static String toHexString(byte[] byteArray) {
        BigInteger bi = new BigInteger(1, byteArray);
        return String.format("%0" + (byteArray.length << 1) + "X", bi);
    }

    public static void main(String[] args) {
        byte[] byteArray = { (byte) 0xFF, (byte) 0x00, (byte) 0x7F };
        System.out.println(toHexString(byteArray));
    }
}

Output :

FF007F

Explanation:

This program uses the BigInteger class and the format method of the String class to convert a byte array to its hexadecimal representation. The toHexString method takes a byte array as input and creates a new BigInteger object with the byte array. The format method is then used to create a string representation of the BigInteger, with the number of digits equal to twice the length of the byte array. The main method demonstrates how to use the toHexString method by creating a byte array and printing its hexadecimal representation.

Example 2 :

Run
import java.math.BigInteger;
import java.util.Arrays;

public class Main {
    static final char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static void main(String[] args) {
        byte[] byteArray = { (byte) 0xFF, (byte) 0x00, (byte) 0x7F };

        // Using BigInteger and format method
        System.out.println("Method 1: Using BigInteger and format method");
        System.out.println(toHexString(byteArray));
        System.out.println();

        // Using a loop and a lookup table
        System.out.println("Method 2: Using a loop and a lookup table");
        System.out.println(toHexStringWithLookup(byteArray));
        System.out.println();

        // Using Arrays.toString
        System.out.println("Method 3: Using Arrays.toString");
        System.out.println(toHexStringWithArrays(byteArray));
        System.out.println();

    }

    public static String toHexString(byte[] byteArray) {
        BigInteger bi = new BigInteger(1, byteArray);
        return String.format("%0" + (byteArray.length << 1) + "X", bi);
    }

    public static String toHexStringWithLookup(byte[] byteArray) {
        char[] hexChars = new char[byteArray.length * 2];
        for (int j = 0; j < byteArray.length; j++) {
            int v = byteArray[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static String toHexStringWithArrays(byte[] byteArray) {
        StringBuilder sb = new StringBuilder();
        for (byte b : byteArray) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}

Output :

Method 1: Using BigInteger and format method
FF007F

Method 2: Using a loop and a lookup table
FF007F

Method 3: Using Arrays.toString
FF007F

Explanation:

The above code provides three different methods for converting a byte array to its hexadecimal representation in Java:

  1. Method 1: Using BigInteger and format method: This method uses the BigInteger class and the format method to convert the byte array to its hexadecimal representation. The BigInteger class is used to convert the byte array to a BigInteger object, and the format method is used to convert the BigInteger object to a hexadecimal string. The format method takes a string that specifies the format of the output, with %0 indicating that the output should be zero-padded, the number of X’s indicating the number of digits in the output, and X indicating that the output should be in uppercase hexadecimal.
  2. Method 2: Using a loop and a lookup table: This method uses a loop and a lookup table to convert the byte array to its hexadecimal representation. The loop iterates through each byte in the array and uses bitwise operations to extract the individual bits of the byte. The lookup table is an array of hexadecimal characters that are used to convert the bits to their corresponding hexadecimal representation.
  3. Method 3: Using Arrays.toString: This method uses StringBuilder class to convert the byte array to its hexadecimal representation. It iterates through each byte in the array and appends the hexadecimal representation of the byte to a StringBuilder object, which is then returned as a string.

All methods will output the same hexadecimal representation of the byte array, you can use any method based on your requirement and ease of use. The output of each method will be a string containing the hexadecimal representation of the byte array, with each byte represented by two hexadecimal characters.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription