Convert hex String To Bytes - Java java.lang

Java examples for java.lang:String Hex

Description

Convert hex String To Bytes

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String hexString = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(hexStringToBytes(hexString)));
    }/*  w w  w. j  a  v  a2 s  . c  om*/

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.length() == 0) {
            return null;
        }

        hexString = hexString.replaceAll(" ", ""); //remove all blankspace
        hexString = hexString.toUpperCase();
        if (hexString.length() % 2 != 0) {
            hexString = hexString.concat("0");
        }
        char[] hexChars = hexString.toCharArray();
        int bytesLen = (hexString.length() + 1) / 2;
        byte[] desBytes = new byte[bytesLen];
        int pos = 0;

        for (int i = 0; i < desBytes.length; i++) {
            pos = i * 2;
            desBytes[i] = (byte) ((charToByte(hexChars[pos]) << 4) | charToByte(hexChars[pos + 1]));
        }

        return desBytes;
    }

    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}

Related Tutorials