Turns a hex encoded string into a byte array. - Java java.lang

Java examples for java.lang:String Hex

Description

Turns a hex encoded string into a byte array.

Demo Code

public class Main {
  public static void main(String[] argv) {
    String hex = "java2s.com";
    System.out.println(java.util.Arrays.toString(decodeHex(hex)));
  }/*from  w w  w .j  av  a 2  s. c o m*/

  /**
   * Turns a hex encoded string into a byte array. It is specifically meant to
   * "reverse" the toHex(byte[]) method.
   *
   * @param hex
   *          a hex encoded String to transform into a byte array.
   * @return a byte array representing the hex String[
   */
  public static final byte[] decodeHex(String hex) {
    char[] chars = hex.toCharArray();
    byte[] bytes = new byte[chars.length / 2];
    int byteCount = 0;
    for (int i = 0; i < chars.length; i += 2) {
      byte newByte = 0x00;
      newByte |= hexCharToByte(chars[i]);
      newByte <<= 4;
      newByte |= hexCharToByte(chars[i + 1]);
      bytes[byteCount] = newByte;
      byteCount++;
    }
    return bytes;

  }

  /**
   * Returns the the byte value of a hexadecimal char (0-f). It's assumed that
   * the hexidecimal chars are lower case as appropriate.
   *
   * @param ch
   *          a hexedicmal character (0-f)
   * @return the byte value of the character (0x00-0x0F)
   */
  private static final byte hexCharToByte(char ch) {
    switch (ch) {
    case '0':
      return 0x00;
    case '1':
      return 0x01;
    case '2':
      return 0x02;
    case '3':
      return 0x03;
    case '4':
      return 0x04;
    case '5':
      return 0x05;
    case '6':
      return 0x06;
    case '7':
      return 0x07;
    case '8':
      return 0x08;
    case '9':
      return 0x09;
    case 'a':
      return 0x0A;
    case 'b':
      return 0x0B;
    case 'c':
      return 0x0C;
    case 'd':
      return 0x0D;
    case 'e':
      return 0x0E;
    case 'f':
      return 0x0F;
    }
    return 0x00;
  }

}

Related Tutorials