[java] How to convert hex strings to byte values in Java

I have a String array. I want to convert it to byte array. I use the Java program. For example:

String str[] = {"aa", "55"};

convert to:

byte new[] = {(byte)0xaa, (byte)0x55};

What can I do?

This question is related to java hex byte

The answer is


Convert string to Byte-Array:

byte[] theByteArray = stringToConvert.getBytes();

Convert String to Byte:

 String str = "aa";

 byte b = Byte.valueOf(str);

Here, if you are converting string into byte[].There is a utility code :

    String[] str = result.replaceAll("\\[", "").replaceAll("\\]","").split(", ");
    byte[] dataCopy = new byte[str.length] ;
    int i=0;
    for(String s:str ) {
        dataCopy[i]=Byte.valueOf(s);
        i++;
    }
    return dataCopy;

Since there was no answer for hex string to single byte conversion, here is mine:

private static byte hexStringToByte(String data) {
    return (byte) ((Character.digit(data.charAt(0), 16) << 4)
                  | Character.digit(data.charAt(1), 16));
}

Sample usage:

hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16

Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.

// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201

You can try something similar to this :

String s = "65";

byte value = Byte.valueOf(s);

Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.


String source = "testString";
byte[] byteArray = source.getBytes(encoding); 

You can foreach and do the same with all the strings in the array.


The simplest way (using Apache Common Codec):

byte[] bytes = Hex.decodeHex(str.toCharArray());

A long way to go :). I am not aware of methods to get rid of long for statements

ArrayList<Byte> bList = new ArrayList<Byte>();
for(String ss : str) {
    byte[] bArr = ss.getBytes();
    for(Byte b : bArr) {
        bList.add(b);
    }
}
//if you still need an array
byte[] bArr = new byte[bList.size()];
for(int i=0; i<bList.size(); i++) {
    bArr[i] = bList.get(i);
}

String str[] = {"aa", "55"};

byte b[] = new byte[str.length];

for (int i = 0; i < str.length; i++) {
    b[i] = (byte) Integer.parseInt(str[i], 16);
}

Integer.parseInt(string, radix) converts a string into an integer, the radix paramter specifies the numeral system.

Use a radix of 16 if the string represents a hexadecimal number.
Use a radix of 2 if the string represents a binary number.
Use a radix of 10 (or omit the radix paramter) if the string represents a decimal number.

For further details check the Java docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)


String str = "Your string";

byte[] array = str.getBytes();