Java Program to Convert Byte Array to Hex String
Last Updated :
14 Feb, 2023
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,
- Iterate through each byte in the array and calculate its hexadecimal equivalent.
- The string.format() is used to print the number of places of a hexadecimal value and store the value in a string.
- %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);
}
}
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);
}
}
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));
}
}
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);
}
}
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read