Java Byte Array Create toBytes(String hexStr)

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

Description

Converts a hexadecimal ASCII string to a byte array.

License

Open Source License

Parameter

Parameter Description
hexStr The string representing a hexadecimal number

Return

the byte array of hexStr

Declaration

public static byte[] toBytes(String hexStr) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from  w w  w.ja  v a 2  s. com*/
     * Converts a hexadecimal ASCII string to a byte array. The method is case
     * insensitive, so F7 works as well as f7. The string should have
     * the form F7d820 and should omit the '0x'.
     * This method is the reverse of <code>toHexString</code>.
     *
     * @param hexStr The string representing a hexadecimal number
     * @return the byte array of hexStr
     * @see #toHexString(byte[])
     */
    public static byte[] toBytes(String hexStr) {
        byte mask = (byte) 0x7F;
        byte[] bytes = new byte[0];

        if (hexStr != null) {
            hexStr = hexStr.toUpperCase();
            int len = hexStr.length();
            bytes = new byte[(len / 2)];
            int sPos = 0; // position in hexStr
            int bPos = 0; // position in bytes
            while (sPos < len) {
                char a = hexStr.charAt(sPos);
                char b = hexStr.charAt(sPos + 1);

                int v1 = Character.digit(a, 16);
                int v2 = Character.digit(b, 16);
                int v3 = (int) (v1 * 16 + v2);
                bytes[bPos] = (byte) v3;

                sPos += 2;
                bPos++;
            }
        }
        return bytes;
    }
}

Related

  1. toBytes(String hex)
  2. toBytes(String hex)
  3. toBytes(String hex)
  4. toBytes(String hex)
  5. toBytes(String hexStr)
  6. toBytes(String hexString)
  7. toBytes(String hexString)
  8. toBytes(String name)
  9. toBytes(String s)