Convert Hex String to byte Array in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Nov-2018 12:21:04
Advertisements