Android Hex String Create hexToBytes(String hex)

Here you can find the source of hexToBytes(String hex)

Description

hex To Bytes

License

Apache License

Declaration

public static byte[] hexToBytes(String hex) 

Method Source Code

//package com.java2s;
/**/*from   ww w. j av a 2 s  .  c  om*/
 * Source obtained from crypto-gwt. Apache 2 License.
 * https://code.google.com/p/crypto-gwt/source/browse/crypto-gwt/src/main/java/com/googlecode/
 * cryptogwt/util/ByteArrayUtils.java
 */

public class Main {
    public static byte[] hexToBytes(String hex) {
        hex = removeSpaces(hex); // Remove spaces
        assert hex.length() % 2 == 0 : "must be even number of bytes";
        int resultLen = hex.length() / 2;
        byte[] result = new byte[resultLen];
        int j = 0;
        for (int i = 0; i < resultLen; i++) {
            result[i] = (byte) (Byte.parseByte(hex.substring(j, ++j), 16) << 4 | Byte
                    .parseByte(hex.substring(j, ++j), 16));
        }
        return result;
    }

    private static String removeSpaces(String string) {
        string = string.replaceAll("\\s+", "");
        return string;
    }
}

Related

  1. appendHex(StringBuffer stringbuffer, byte byte0)
  2. toHexString(char achar0)
  3. decodeHexStr(final String str)
  4. hexDigest(String input)
  5. hexToBt64(String hex)
  6. convertToHex(byte[] data)
  7. convertToHex(byte[] data)
  8. byte2HexStr(byte[] b, int length)
  9. byte2hex(byte[] bytes)