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 Program to Convert Hex String to Byte Array
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. 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
4 min read
Java Program to Convert Byte Array to Image
A byte array is the array of bytes that is used to store the collection of binary data. For example, the byte array of an image stores the information of every pixel of the image. In the byte array, we can store the content of any file in binary format. We can initialize the byte array with the byte
3 min read
Java Program to Convert File to a Byte Array
Here, we will go through the different ways to convert file to byte array in Java. Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs. Methods: Using rea
3 min read
Java Program to Convert Byte Array to Long
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. Given an array of bytes, convert it to a long value. Example: Byte Array: 1 2 3 4 Long Value: 16909060 Equivalent Hexadecimal String: 0x1020304 There are numerous approaches fo
3 min read
Java Program to Convert String to Byte Array Using getBytes() Method
In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getByte() method. It is the easiest way to convert a string to a byte array. This method converts the given string to a sequence of bytes using the platform's default charset an
2 min read
Java Program to Convert Byte Array to Object
Converting byte array into Object and Object into a byte array process is known as deserializing and serializing. The class object which gets serialized/deserialized must implement the interface Serializable. Serializable is a marker interface that comes under package 'java.io.Serializable'.Byte Arr
2 min read
Java Program to Convert String to InputStream
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations. Illustration: Input : String : "Geeks for Geeks" Output : Input Stream : Geeks for Geeks Input : String : "A computer science portal" Output : Input stream : A computer science portal In order
2 min read
Java Program to Convert InputStream to String
Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read
4 min read
Java Program to Convert Char to Byte
Given a char in Java, the task is to write a Java program that converts this char into Byte. Examples: Input: ch = 'A' Output: 65 Input: ch = 'B' Output 66 In Java, char is a primitive data type and it is used to declare characters. It has the capability to hold 16-bit unsigned Unicode characters. T
3 min read
Java Program to Convert Binary to Hexadecimal
The Hexadecimal number system as the name suggests comprises 16 entities. These 16 entities consist of 10 digits, 0-9 representing the first 10 numbers of the hexadecimal system as well. For the remaining 6 numbers, we use English alphabets ranging from A through F to represent the numbers 10 to 15.
6 min read