Java Program to Convert Hex String to Byte Array
Last Updated :
24 Sep, 2021
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 array is 0.
Given a byte array, the task is to convert the Hex String to Byte Array.
Example:
Input - Hex String : "2f4a33"
Output - Byte Array : 47 74 51
Input - Hex String : "3b4a11"
Output - Byte Array : 59 74 17
There are numerous approaches for converting a Hex String to Byte Array, and a few of them are listed below.
Approaches:
- Using parseInt() method of Integer class in Java
- Using Byte Array Representation of BigInteger in Java
- Using Bitwise Shift Operators
Approach 1 - Using parseInt() method of Integer class in Java
The integer.parseInt() method in Java converts a given string to an integer. According to the given problem statement, since we have to convert a hex string to a byte array, we will first convert the characters of the hex string in pairs to the specific byte formation and insert that number into the byte array. In this, the byte array is initialized with a size of half the length of the hex string.
Following is the implementation of the foregoing approach -
Java
// Java Program to convert hex
// string to byte array
// Approach 1 - Using parseInt() method of
// Integer class in Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Initializing the hex string and byte array
String s = "2f4a33";
byte[] ans = new byte[s.length() / 2];
System.out.println("Hex String : "+s);
for (int i = 0; i < ans.length; i++) {
int index = i * 2;
// Using parseInt() method of Integer class
int val = Integer.parseInt(s.substring(index, index + 2), 16);
ans[i] = (byte)val;
}
// Printing the required Byte Array
System.out.print("Byte Array : ");
for (int i = 0; i < ans.length; i++) {
System.out.print(ans[i] + " ");
}
}
}
OutputHex String : 2f4a33
Byte Array : 47 74 51
Approach 2 - Using Byte Array Representation of BigInteger in Java
In this approach, we will use the toByteArray() method of BigInteger class. After converting the hexadecimal number to an integer value using the parseInt() method, we are left to convert integers to a byte array. Here comes the role of toByteArray() method of BigInteger class which will transform the integer values to a byte array and return it.
Following is the implementation of the foregoing approach -
Java
// Java Program to convert hex
// string to byte array
// Approach 1 - Using Byte Array Representation
// of BigInteger in Java
import java.io.*;
// importing BigInteger class
import java.math.BigInteger;
class GFG {
public static void main(String[] args)
{
String s = "3b4a11";
// converting string to integer value
int val = Integer.parseInt(s, 16);
System.out.println("Hexadecimal String : " + s);
// converting integer value to Byte Array
BigInteger big = BigInteger.valueOf(val);
byte[] ans = (big.toByteArray());
// printing the byte array
System.out.print("Byte Array : ");
for (int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
}
}
OutputHexadecimal String : 3b4a11
Byte Array : 59 74 17
Approach 3 - Using Bitwise Shift Operators
Another way to convert a hex string to a byte array is to use the Binary shift operators of Java. Here “<<” bitwise left shift operator is used. In order to get the numeric value of the character in hexadecimal order, the Character.digit() method in Java is used.
Following is the implementation of the foregoing approach -
Java
// Java program to convert hex
// string to byte array
// Approach 3 - Using Bitwise Shift Operators
import java.io.*;
class GFG {
public static void main (String[] args) {
// initializing hex string and byte array
String s ="1f3d44";
System.out.println("Hex String : " + s);
int len = s.length();
byte[] ans = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
// using left shift operator on every character
ans[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
// printing the required result
System.out.print("Byte Array : ");
for(int i=0;i<ans.length;i++){
System.out.print(ans[i]+" ");
}
}
}
OutputHex String : 1f3d44
Byte Array : 31 61 68
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 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
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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 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
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
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
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 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