get Byte Array By Hex String - Android java.lang

Android examples for java.lang:Byte Array

Description

get Byte Array By Hex String

Demo Code

import android.util.Base64;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;

public class Main{
    public static final String HEX_STRING_BLANK_SPLIT = " ";
    public static final String HEX_STRING_NOT_SPLIT = "";
    public static byte[] getByteArrayByHexString(String hex) {
        return getByteArrayByHexString(hex,
                HEX_STRING_BLANK_SPLIT);
    }// ww  w  .ja  va  2s  . c  om
    public static byte[] getByteArrayByHexString(String hex,
            String splitString) {
        String[] hexArrays = null;
        if (splitString.equals(HEX_STRING_NOT_SPLIT)) {
            hexArrays = new String[hex.length() / 2];
            for (int i = 0; i < hexArrays.length; i++) {
                hexArrays[i] = hex.substring(i * 2, i * 2 + 2);
            }
        } else {
            hexArrays = hex.split(splitString);
        }
        byte[] b = new byte[hexArrays.length];
        for (int i = 0; i < hexArrays.length; i++) {
            b[i] = (byte) Integer.parseInt(hexArrays[i], 16);
        }
        return b;
    }

}

Related Tutorials