0

Is there any function in Java that converts a string to a byte array?

Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
silverkid
  • 9,291
  • 22
  • 66
  • 92
  • Duplicate of http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java – Stephen C Dec 16 '09 at 10:12
  • possible duplicate of [Convert string to byte\[\]](http://stackoverflow.com/questions/228987/convert-string-to-byte) –  Aug 28 '12 at 15:55

3 Answers3

5

Yes: String.getBytes. You really, really want to specify the character encoding when you do so though - using the platform default encoding is almost always the wrong thing to do.

Ideally, it's best to specify the encoding via a Charset - that way you don't need to worry about the UnsupportedEncodingException which can be thrown by the overload of getBytes which just takes a String with the character encoding name as an argument.

EDIT: Based on your comment, it looks like you want to parse a hex string into a byte array. (It would have been useful to say so in your question.) String.getBytes is inappropriate for this - I don't believe there's anything which does this in the standard libraries, but the Apache Commons Codec library makes it pretty easy:

byte[] data = Hex.decodeHex(text.toCharArray());
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @silverkid: You mean you want to *parse* a string of hex digits into a byte array? Editing... – Jon Skeet Dec 16 '09 at 10:07
  • yes i have a string of hex digits that i want to convert to byte array – silverkid Dec 16 '09 at 10:08
  • for example my string is 95A8EE8E89979B9EFDCBC6EB9797528D – silverkid Dec 16 '09 at 10:09
  • Using the deprecated version of the getBytes method is 10x faster than newer, correct versions. We use the older method in logging code where encoding issues are not a concern. ref: http://java.sun.com/developer/technicalArticles/Programming/Performance/ – Jim Rush Dec 16 '09 at 12:16
  • 1
    Where can encoding issues not be a concern? If you don't care about the output, why bother calling the method? I'd also question the wisdom of trusting performance advice from 12 years ago... – Jon Skeet Dec 16 '09 at 13:55
1

String.getBytes()?

Ash
  • 9,296
  • 2
  • 24
  • 32
0

Have you tried?

"whatever".getBytes()
Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
ATorras
  • 4,073
  • 2
  • 32
  • 39