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

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

Description

hex String To Bytes

Parameter

Parameter Description
hex a parameter

Declaration

public static byte[] hexStringToBytes(String hex) 

Method Source Code

//package com.java2s;

public class Main {
    /**/* ww  w  .  j  a v a  2  s .c  om*/
     *
     * @param hex
     * @return
     */
    public static byte[] hexStringToBytes(String hex) {
        int len = (hex.length() / 2);
        byte[] res = new byte[len];
        char[] c = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            res[i] = (byte) (toByte(c[pos]) << 4 | toByte(c[pos + 1]));
        }

        return res;
    }

    /**
     *
     * @param c
     * @return
     */
    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);

        return b;
    }
}

Related

  1. fromHex(String hex)
  2. fromHex(String hexData)
  3. hexStringToByteArray(String s)
  4. hexStringToBytes(String hex)
  5. hexStringToBytes(String hexString)
  6. hexStringToBytes(String hexString)
  7. toByte(String hexString)