Android String to Hex Byte Array Convert hexStringToBytes(String hexString)

Here you can find the source of hexStringToBytes(String hexString)

Description

Convert hex string to byte[]

Parameter

Parameter Description
hexString the hex string

Return

byte[]

Declaration

public static byte[] hexStringToBytes(String hexString) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from  w w  w. java 2s .  c o m
     * Convert hex string to byte[]
     * 
     * @param hexString
     *            the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     * 
     * @param c
     *            char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}

Related

  1. stringToHexByte(String str)
  2. hexStr2Bytes(String src)
  3. hexStringToBytes(String hex)
  4. getBytes(String hexString)
  5. hexStringToBytes(String hexString)