Android Utililty Methods String to Hex Byte Array Convert

List of utility methods to do String to Hex Byte Array Convert

Description

The list of methods to do String to Hex Byte Array Convert are organized into topic(s).

Method

byte[]fromHexString(String s)
from Hex String
char[] rawChars = s.toUpperCase().toCharArray();
int hexChars = 0;
for (char rawChar1 : rawChars) {
    if ((rawChar1 >= '0' && rawChar1 <= '9')
            || (rawChar1 >= 'A' && rawChar1 <= 'F')) {
        hexChars++;
byte[] byteString = new byte[(hexChars + 1) >> 1];
int pos = hexChars & 1;
for (char rawChar : rawChars) {
    if (rawChar >= '0' && rawChar <= '9') {
        byteString[pos >> 1] <<= 4;
        byteString[pos >> 1] |= rawChar - '0';
    } else if (rawChar >= 'A' && rawChar <= 'F') {
        byteString[pos >> 1] <<= 4;
        byteString[pos >> 1] |= rawChar - 'A' + 10;
    } else {
        continue;
    pos++;
return byteString;
byte[]hexDecode(String data)
hex Decode
byte[] r = new byte[data.length() / 2];
char[] a = data.toCharArray();
for (int i = 0; i < a.length; i += 2) {
    char c1 = a[i], c2 = a[i + 1];
    int v1 = valueOf(c1);
    int v2 = valueOf(c2);
    r[i >> 1] = (byte) ((((v1 & 0xf) << 4) | (v2 & 0xf)) & 0xff);
return r;