0

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

2

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

5 Comments

@silverkid: You mean you want to parse a string of hex digits into a byte array? Editing...
yes i have a string of hex digits that i want to convert to byte array
for example my string is 95A8EE8E89979B9EFDCBC6EB9797528D
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: java.sun.com/developer/technicalArticles/Programming/…
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...
1

String.getBytes()?

Comments

0

Have you tried?

"whatever".getBytes()

1 Comment

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

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.