Java byte array convert from hex string

Description

Java byte array convert from hex string

import java.util.Arrays;

public class Main {
   public static void main(String[] argv){
      byte[] b = hexStringToByte("demo2s.com");
      System.out.println(Arrays.toString(b));
   }/*w  w w . java  2  s .  c  o m*/
  /**
   * Given a hexstring this will return the byte array corresponding to the
   * string
   * @param hex the hex String array
   * @return a byte array that is a hex string representation of the given
   *         string. The size of the byte array is therefore hex.length/2
   */
  public static byte[] hexStringToByte(String hex) {
    byte[] bts = new byte[hex.length() / 2];
    for (int i = 0; i < bts.length; i++) {
      bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
    }
    return bts;
  }
}



PreviousNext

Related