Convert Hex String to byte Array in Java


To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array.

byte[] val = new byte[str.length() / 2];

Now, take a for loop until the length of the byte array.

for (int i = 0; i < val.length; i++) {
   int index = i * 2;
   int j = Integer.parseInt(str.substring(index, index + 2), 16);
   val[i] = (byte) j;
}

Let us see the complete example.

Example

 Live Demo

public class Demo {
   public static void main(String args[]) {
      String str = "p";
      byte[] val = new byte[str.length() / 2];
      for (int i = 0; i < val.length; i++) {
         int index = i * 2;
         int j = Integer.parseInt(str.substring(index, index + 2), 16);
         val[i] = (byte) j;
      }
      System.out.println(val);
   }
}

Output

[B@2a139a55

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements