How to convert hex string to byte Array in Java?

We can convert a hex string to byte array in Java by first converting the hexadecimal number to integer value using the parseInt() method of the Integer class in java. This will return an integer value which will be the decimal conversion of hexadecimal value. We will then use the toByteArray() method of BigInteger class that will return a byte array.


 Live Demo

import java.math.BigInteger;
public class Demo {
   public static void main(String args[]) {
      String str = "1D08A";
      int it = Integer.parseInt(str, 16);
      System.out.println("Hexadecimal String " + str);
      BigInteger bigInt = BigInteger.valueOf(it);
      byte[] bytearray = (bigInt.toByteArray());
      System.out.print("Byte Array : ");
      for(int i = 0; i < bytearray.length; i++)
      System.out.print(bytearray[i]+ "\t");


Hexadecimal String 1D08A
Byte Array : 1 -48 -118