Android Byte Array to Hex Convert decodeHex(char[] data)

Here you can find the source of decodeHex(char[] data)

Description

hex to byte[]

Parameter

Parameter Description
data a parameter

Exception

Parameter Description
RuntimeException an exception

Return

byte[]

Declaration

public static byte[] decodeHex(char[] data) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from w w w.j  av  a2  s .  c o m*/
     * hex to byte[]
     *
     * @param data
     * @return byte[]
     * @throws RuntimeException
     */
    public static byte[] decodeHex(char[] data) {

        int len = data.length;

        if ((len & 0x01) != 0) {
            throw new RuntimeException("Odd number of characters.");
        }

        byte[] out = new byte[len >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f = f | toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    /**
     * hex to int
     *
     * @param ch
     * @param index
     * @return int
     * @throws RuntimeException
     */
    protected static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal character "
                    + ch + " at index " + index);
        }
        return digit;
    }
}

Related

  1. toHex(byte[] buf)
  2. byte2hex(byte[] b)
  3. byte2hex(byte[] b)
  4. hexEncode(byte[] data)
  5. encodeHex(byte[] data)
  6. bytesToHex(byte[] data)
  7. bytesToHexString(byte[] bytesArray)
  8. parseByte2HexStr(byte buf[])
  9. bytesToHex(byte[] bytes)