Reputation: 523
I need to create a String from hex values I'm providing.
For example, instead of assigning like this:
String message = "123";
I want to assign like this:
String message = 0x31, 0x32, 0x33;
Is that possible?
Upvotes: 6
Views: 2176
Reputation: 8680
If you have a String
representation of a Hex value (say, you are getting the value from the server, in a JSON object), you might need to make sure to treat it as a Hex value. You can import import org.apache.commons.codec.binary.Hex;
and then do this:
String stringHex = "a37e7391ebbc939a8489788d93015914eeee423132e2516711e81d53777067ee"
String yourString = new String(Hex.decodeHex(stringHex.toCharArray()), StandardCharsets.UTF_8);
Just wanted to add to the above answer.
Upvotes: 0
Reputation: 11913
You should probably also specify the character set you are using but this will do it:
String message = new String(new byte[] {0x31, 0x32, 0x33});
System.out.println(message); // prints 123.
If you did want to specify the character set it is just another parameter to the String
constructor. The following example will work if targeting Android API 19+:
String message = new String(new byte[] {0x31, 0x32, 0x33}, StandardCharsets.UTF_8);
Upvotes: 7