tags:

views:

256

answers:

3

is there any function in java that converts string to byte array ?

+1  A: 

String.getBytes()?

Ash
+6  A: 

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
for a hex string ?
silverkid
@silverkid: You mean you want to *parse* a string of hex digits into a byte array? Editing...
Jon Skeet
yes i have a string of hex digits that i want to convert to byte array
silverkid
for example my string is 95A8EE8E89979B9EFDCBC6EB9797528D
silverkid
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
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
A: 

Hi,

Have you tried?

"whatever".getBytes()

Regards.

ATorras
It's almost never a good idea to use the platform default encoding.
Jon Skeet