hex To Byte via Character.digit - Java java.lang

Java examples for java.lang:Hex

Description

hex To Byte via Character.digit

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String hexString = "java2s.com";
        System.out.println(java.util.Arrays.toString(hexToByte(hexString)));
    }/*ww w .  ja v  a 2  s.com*/

    public static byte[] hexToByte(String hexString) {
        int len = hexString.length();
        byte[] ba = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            ba[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i + 1), 16));
        }
        return ba;
    }
}

Related Tutorials