English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Convert hexadecimal string to byte array in Java

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

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

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

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

Let's see the complete example.

Example

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;++) {
         int index = i * 2;
         int j = Integer.parseInt(str.substring(index, index + 2), 16);
         val[i] = (byte) j;
      }
      System.out.println(val);
   }
}

Output Result

[B@2a139a55