Java Byte Array Create toBytes(String hex)

Here you can find the source of toBytes(String hex)

Description

Convert Hex string to byte array hex string format is: 2 char represent one byte,can use space as separator for example, "12 1e 3d ee FF 09"

License

Apache License

Parameter

Parameter Description
hex a parameter

Declaration

public static byte[] toBytes(String hex) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from  w w  w. j a va  2  s  .com
     * Convert Hex string to byte array hex string format is: 2 char represent
     * one byte,can use space as separator for example, "12 1e 3d ee FF 09"
     *
     * @param hex
     * @return
     */
    public static byte[] toBytes(String hex) {
        byte[] buff = new byte[hex.length() / 2];

        int s1, s2, count = 0;
        for (int i = 0; i < hex.length(); i++) {
            if (hex.charAt(i) >= '0' && hex.charAt(i) <= '9')
                s1 = hex.charAt(i) - 48;
            else if (hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F')
                s1 = hex.charAt(i) - 55;
            else if (hex.charAt(i) >= 'a' && hex.charAt(i) <= 'f')
                s1 = hex.charAt(i) - 87;
            else
                continue;

            i++;
            if (hex.charAt(i) >= '0' && hex.charAt(i) <= '9')
                s2 = hex.charAt(i) - 48;
            else if (hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F')
                s2 = hex.charAt(i) - 55;
            else if (hex.charAt(i) >= 'a' && hex.charAt(i) <= 'f')
                s2 = hex.charAt(i) - 87;
            else
                continue;

            buff[count] = ((byte) (s1 * 16 + s2));
            count++;
        }
        byte[] result = new byte[count];
        System.arraycopy(buff, 0, result, 0, result.length);
        return result;
    }
}

Related

  1. toBytes(short sVal, byte[] bytes, boolean bigEndian)
  2. toBytes(short value)
  3. toBytes(short value)
  4. toBytes(String hex)
  5. toBytes(String hex)
  6. toBytes(String hex)
  7. toBytes(String hex)
  8. toBytes(String hex)
  9. toBytes(String hexStr)