Java Hex Convert To fromHex(String text)

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

Description

Utility method which converts a hex string to a byte[]

License

Open Source License

Parameter

Parameter Description
text The text to convert

Return

The bytes

Declaration

public static byte[] fromHex(String text) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*ww w . j  a  va 2 s .  com*/
     * Utility method which converts a hex string to a byte[]
     *
     * @param text The text to convert
     * @return The bytes
     */
    public static byte[] fromHex(String text) {
        byte[] result = new byte[text.length() / 2];

        for (int i = 0; i < result.length; i++)
            result[i] = (byte) ((byte) ((byte) 0xf0 & ((getByte(text.charAt(2 * i))) << 4))
                    | getByte(text.charAt(2 * i + 1)));

        return result;
    }

    /**  
     * Utility method for converting a char to a byte
     *
     * @param c The char
     * @return The byte
     */
    protected static byte getByte(char c) {
        if ((c >= '0') && (c <= '9'))
            return (byte) (c - '0');
        else if ((c >= 'A') && (c <= 'F'))
            return (byte) (10 + (byte) (c - 'A'));
        else if ((c >= 'a') && (c <= 'f'))
            return (byte) (10 + (byte) (c - 'a'));
        else
            throw new RuntimeException("Could not decode hex character '" + c + "'");
    }
}

Related

  1. fromHex(String s, boolean hexIsDefault)
  2. fromHex(String src)
  3. fromHex(String str)
  4. fromHex(String str)
  5. fromHex(String string)
  6. fromHex(String[] data)
  7. fromHex2B(String src)
  8. fromHex8B(String src)
  9. fromHexa(String s)