Java Hex to Byte Array convertHexToBytes(String s)

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

Description

Convert a hex encoded string to a byte array.

License

Mozilla Public License

Parameter

Parameter Description
s the hex encoded string

Return

the byte array

Declaration

public static byte[] convertHexToBytes(String s) 

Method Source Code

//package com.java2s;
/*//from   ww w  . ja  v a 2  s. c o  m
 * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
 * and the EPL 1.0 (http://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */

public class Main {
    private static final int[] HEX_DECODE = new int['f' + 1];

    /**
     * Convert a hex encoded string to a byte array.
     *
     * @param s the hex encoded string
     * @return the byte array
     */
    public static byte[] convertHexToBytes(String s) {
        int len = s.length();
        if (len % 2 != 0) {
            throw new RuntimeException("HEX_STRING_ODD:" + s);
        }
        len /= 2;
        byte[] buff = new byte[len];
        int mask = 0;
        int[] hex = HEX_DECODE;
        try {
            for (int i = 0; i < len; i++) {
                int d = hex[s.charAt(i + i)] << 4 | hex[s.charAt(i + i + 1)];
                mask |= d;
                buff[i] = (byte) d;
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RuntimeException("HEX_STRING_WRONG:" + s, e);
        }
        if ((mask & ~255) != 0) {
            throw new RuntimeException("HEX_STRING_WRONG:" + s);
        }
        return buff;
    }
}

Related

  1. convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte)
  2. convertHexStringToByteNoSpace(String s)
  3. convertHexStringToBytes(String hex)
  4. convertHexStringToBytes(String hex)
  5. convertHexToByteArray(String hexString)
  6. convertHexToBytes(String s)