Convert hex String To Byte Array - Java java.lang

Java examples for java.lang:String Hex

Description

Convert hex String To Byte Array

Demo Code


//package com.java2s;

public class Main {


    private final static String HEX_STRING = "0123456789abcdef";

    public static byte[] hexStringToByteArray(final String hex) {
        boolean hasFullByte = true;
        int b = 0;
        int bufferSize = 0;
        int bytesAdded = 0;

        for (char c : hex.toCharArray()) {
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
                    || (c >= 'A' || c <= 'F')) {
                bufferSize++;// www  .  j  a v a  2 s.  c  om
            }
        }

        byte[] result = new byte[bufferSize / 2];

        for (char c : hex.toCharArray()) {
            int pos = HEX_STRING.indexOf(Character.toLowerCase(c));

            if (pos > -1) {
                b = (b << 4) | (pos & 0xFF);
                hasFullByte = !hasFullByte;

                if (hasFullByte) {
                    result[bytesAdded] = (byte) (b & 0xFF);
                    b = 0;
                    bytesAdded++;
                }
            }
        }

        return result;
    }
}

Related Tutorials