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?

3
  • 1
    See stackoverflow.com/questions/140131/… Commented Dec 28, 2011 at 7: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. Commented Sep 8, 2017 at 6:29
  • @backslashN: Won't the result be like {97, 97} and {53, 53}? Commented Jul 25, 2018 at 13:10

10 Answers 10

54
String str = "Your string";

byte[] array = str.getBytes();
Sign up to request clarification or add additional context in comments.

2 Comments

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).
byte[] array = str.getBytes("UTF-8"); throws UnsupportedEncodingException
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;
    

Comments

11

Convert string to Byte-Array:

byte[] theByteArray = stringToConvert.getBytes();

Convert String to Byte:

 String str = "aa";

 byte b = Byte.valueOf(str);

1 Comment

it gives me NumberFormatException when enter a value from A to F
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.

2 Comments

It does not works. java.lang.NumberFormatException: unable to parse 'aa' as integer
That means it was an empty string
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);
}

Comments

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

1 Comment

This is the best method for me
2
String source = "testString";
byte[] byteArray = source.getBytes(encoding); 

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

1 Comment

My mean is change (String)"aa" to (byte)0xaa, but not to (byte)0x97, (byte)0x97
0

The simplest way (using Apache Common Codec):

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

Comments

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)

1 Comment

Code-only answers don't explain why the code works: please add an explanation for future visitors what you did to solve the problem.
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.