Java Byte Array Create toBytesFromString(String s)

Here you can find the source of toBytesFromString(String s)

Description

Returns a byte array from a string of hexadecimal digits.

License

Open Source License

Parameter

Parameter Description
s a string of hexadecimal ASCII characters

Return

the decoded byte array from the input hexadecimal string.

Declaration

public static byte[] toBytesFromString(String s) 

Method Source Code

//package com.java2s;
// under the terms of the GNU General Public License as published by the Free

public class Main {
    /**/*from   w  w  w  . j a  v  a 2s .c  om*/
     * <p>Returns a byte array from a string of hexadecimal digits.</p>
     *
     * @param s a string of hexadecimal ASCII characters
     * @return the decoded byte array from the input hexadecimal string.
     */
    public static byte[] toBytesFromString(String s) {
        int limit = s.length();
        byte[] result = new byte[((limit + 1) / 2)];
        int i = 0, j = 0;
        if ((limit % 2) == 1) {
            result[j++] = (byte) fromDigit(s.charAt(i++));
        }
        while (i < limit) {
            result[j++] = (byte) ((fromDigit(s.charAt(i++)) << 4) | fromDigit(s.charAt(i++)));
        }
        return result;
    }

    /**
     * <p>Returns a number from <code>0</code> to <code>15</code> corresponding
     * to the designated hexadecimal digit.</p>
     *
     * @param c a hexadecimal ASCII symbol.
     */
    public static int fromDigit(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else if (c >= 'A' && c <= 'F') {
            return c - 'A' + 10;
        } else if (c >= 'a' && c <= 'f') {
            return c - 'a' + 10;
        } else
            throw new IllegalArgumentException("Invalid hexadecimal digit: " + c);
    }
}

Related

  1. toBytesFromBase64(String inBase64String)
  2. toBytesFromBin(String binSymbols)
  3. toBytesFromHexStr(String hexStr)
  4. toBytesFromHexString(String digits)
  5. toBytesFromOct(String octSymbols)
  6. toBytesFromUnicode(String s)
  7. toBytesHexEscaped(final byte[] s, final int off, final int len)
  8. toBytesInt32BE(int w)
  9. toBytesLittleEndian(long value, int cnt)