22

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?

U. Windl
  • 3,480
  • 26
  • 54
brian
  • 6,802
  • 29
  • 83
  • 124
  • 1
    See http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java – rafraf Dec 28 '11 at 07:22
  • 2
    `byte n[] = str.getBytes()` will do the task. However, you'll get error on `new` as it is a keyword and cannot be used as identifier. – backslashN Sep 08 '17 at 06:29
  • @backslashN: Won't the result be like `{97, 97}` and `{53, 53}`? – U. Windl Jul 25 '18 at 13:10

10 Answers10

54
String str = "Your string";

byte[] array = str.getBytes();
Lion
  • 18,729
  • 22
  • 80
  • 110
  • 3
    Always specify a specific character set like `UTF-8` unless the default platform dependent character set is adequate (which is undesirable in most cases) using one of the overloaded versions of that method such as `String#getBytes(Charset charset)` or `String#getBytes(String charsetName)`. – Tiny Jan 29 '16 at 18:59
  • byte[] array = str.getBytes("UTF-8"); throws UnsupportedEncodingException – daddygames Sep 07 '17 at 19:43
15

Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?

If yes, then for each string item I would do the following:

  1. check that a string consists only of 2 characters
  2. these chars are in '0'..'9' or 'a'..'f' interval (take their case into account as well)
  3. convert each character to a corresponding number, subtracting code value of '0' or 'a'
  4. build a byte value, where first char is higher bits and second char is lower ones. E.g.

    int byteVal = (firstCharNumber << 4) | secondCharNumber;
    
TT--
  • 2,956
  • 1
  • 27
  • 46
Wizart
  • 940
  • 5
  • 8
11

Convert string to Byte-Array:

byte[] theByteArray = stringToConvert.getBytes();

Convert String to Byte:

 String str = "aa";

 byte b = Byte.valueOf(str);
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
9

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.

Mithun Sasidharan
  • 20,572
  • 10
  • 34
  • 52
3

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
mr5
  • 3,438
  • 3
  • 40
  • 57
3

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);
}
suat
  • 4,239
  • 3
  • 28
  • 51
2
String source = "testString";
byte[] byteArray = source.getBytes(encoding); 

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

Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
0

The simplest way (using Apache Common Codec):

byte[] bytes = Hex.decodeHex(str.toCharArray());
ANTARA
  • 810
  • 1
  • 13
  • 20
0
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)

h3k
  • 23
  • 5
  • 1
    Code-only answers don't explain why the code works: please add an explanation for future visitors what you did to solve the problem. – Alex Huszagh Jun 30 '17 at 23:03
0

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;