37
String str = "9B7D2C34A366BF890C730641E6CECF6F";

I want to convert str into byte array, but str.getBytes() returns 32 bytes instead of 16.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Qaiser Mehmood
  • 975
  • 6
  • 21
  • 33
  • 4
    That's not a bug at all. – Buhake Sindi Jul 11 '11 at 13:19
  • 1
    Some valid java code would be helpful... – Andreas Dolk Jul 11 '11 at 13:19
  • @JB Nizet - pretty sure, that the String has 16 characters, each and everyone encoded 16 bit. Which results in - still not really surprising - 32 bytes. Java uses UTF16 internally, 1 char = 2 bytes. – Andreas Dolk Jul 11 '11 at 13:28
  • 1
    @Andreas_D: Look at the question of the OP. The STring has 32 characters. Moreover String.getBytes() doesn't return the internal representation of the String as bytes. It returns the String as a byte array, using the default platform encoding (which might be UTF8, ISO8859-1, CP-1252, ..., using 1 byte per ASCII char) – JB Nizet Jul 11 '11 at 13:34
  • 1
    @JB Nizet - the question does not include valid Java code and it is *my* interpretation that the *stringy thing* is a 16 byte integer value in hex format. (that's why I recommended *valid java code* in my first comment) – Andreas Dolk Jul 11 '11 at 13:44
  • 1
    OK. Understood. Without a correct question, hard to give a correct answer. – JB Nizet Jul 11 '11 at 13:48

7 Answers7

56

I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.

The apache commons-codec has a class for that, Hex.

String s = "9B7D2C34A366BF890C730641E6CECF6F";    
byte[] bytes = Hex.decodeHex(s.toCharArray());
Alex S
  • 25,241
  • 18
  • 52
  • 63
pap
  • 27,064
  • 6
  • 41
  • 46
38

Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

The method is DatatypeConverter.parseHexBinary

In this case it can be used as follows:

String str = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = DatatypeConverter.parseHexBinary(str);

The class also provides type conversions for many other formats that are generally used in XML.

Diego Allen
  • 4,623
  • 5
  • 30
  • 33
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • 2
    The simplest solution for this question that I came across so far - thanks! – mh. Dec 12 '12 at 14:45
  • 6
    This should have been the accepted answer since it's the simplest solution that utilises only the core Java libraries. – MTCoster Aug 27 '13 at 17:08
5

Use:

str.getBytes("UTF-16LE");
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • It gives output like [B@405e898, but I want the same Str String as Byte Array. – Qaiser Mehmood Jul 11 '11 at 13:33
  • @Qaiser Mehmood Becuase it's an array so you cannot just print it, you have to make a simple loop to print its elements one by one – Eng.Fouad Jul 11 '11 at 13:47
  • Something like: `for(byte b : str.getBytes("UTF-16LE")) System.out.println(b);` – Eng.Fouad Jul 11 '11 at 13:49
  • 1
    That won't convert a hex string to the corresponding bytes. That will convert any string to its UTF16 encoding. By the way, with OP's example string, it will spit out 64 bytes, which is totally not what was requested. – dim Nov 21 '18 at 10:24
2

I know it's late but hope it will help someone else...

This is my code: It takes two by two hex representations contained in String and add those into byte array. It works perfectly for me.

public byte[] stringToByteArray (String s) {
    byte[] byteArray = new byte[s.length()/2];
    String[] strBytes = new String[s.length()/2];
    int k = 0;
    for (int i = 0; i < s.length(); i=i+2) {
        int j = i+2;
        strBytes[k] = s.substring(i,j);
        byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
        k++;
    }
    return byteArray;
}
0

try this:

     String str = "9B7D2C34A366BF890C730641E6CECF6F";
     String[] temp = str.split(",");
     bytesArray = new byte[temp.length];
     int index = 0;
     for (String item: temp) {
     bytesArray[index] = Byte.parseByte(item);
     index++;
     }
G M Ramesh
  • 3,420
  • 9
  • 37
  • 53
0

I assume what you need is to convert a hex string into a byte array that equals that means the same thing as that hex string? Adding this method should do it for you, without any extra library importing:

public static byte[] hexToByteArray(String s) {
     String[] strBytes = s.split("(?<=\\G.{2})");
     byte[] bytes = new byte[strBytes.length];
     for(int i = 0; i < strBytes.length; i++)
         bytes[i] = (byte)Integer.parseInt(strBytes[i], 16);
     return bytes;
}
0

That should do the trick :

byte[] bytes = toByteArray(Str.toCharArray());

public static byte[] toByteArray(char[] array) {
    return toByteArray(array, Charset.defaultCharset());
}

public static byte[] toByteArray(char[] array, Charset charset) {
    CharBuffer cbuf = CharBuffer.wrap(array);
    ByteBuffer bbuf = charset.encode(cbuf);
    return bbuf.array();
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118