Is there any function in Java that converts a string to a byte array?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 theUnsupportedEncodingExceptionwhich can be thrown by the overload ofgetByteswhich 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.getBytesis 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: