Java Hex Convert To fromHex(String encoded)

Here you can find the source of fromHex(String encoded)

Description

Decode hex string to a byte array

License

Apache License

Parameter

Parameter Description
encoded encoded string

Return

return array of byte to encode

Declaration

static public byte[] fromHex(String encoded) 

Method Source Code

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

public class Main {
    static private final int BASELENGTH = 128;
    static final private byte[] hexNumberTable = new byte[BASELENGTH];

    /**/* w w  w .  java2 s . c  o m*/
     * Decode hex string to a byte array
     *
     * @param encoded encoded string
     * @return return array of byte to encode
     */
    static public byte[] fromHex(String encoded) {
        if (encoded == null)
            throw new NullPointerException();

        int lengthData = encoded.length();

        if (lengthData % 2 != 0)
            throw new IllegalStateException("bad string :" + encoded);

        char[] binaryData = encoded.toCharArray();
        int lengthDecode = lengthData / 2;
        byte[] decodedData = new byte[lengthDecode];
        byte temp1, temp2;
        char tempChar;
        for (int i = 0; i < lengthDecode; i++) {
            tempChar = binaryData[i * 2];
            temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
            if (temp1 == -1)
                throw new IllegalStateException("bad string :" + encoded);
            tempChar = binaryData[i * 2 + 1];
            temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
            if (temp2 == -1)
                throw new IllegalStateException("bad string :" + encoded);
            decodedData[i] = (byte) ((temp1 << 4) | temp2);
        }
        return decodedData;
    }
}

Related

  1. fromHex(final String hex)
  2. fromHex(final String hexValue)
  3. fromHex(final String s)
  4. fromHex(final String string, final int offset, final int count)
  5. fromHex(String bytesString)
  6. fromHex(String hex)
  7. fromHex(String hex)
  8. fromHex(String hex)
  9. fromHex(String hex)