sonia sonia - 2 months ago 6
Java Question

Wich charset for converting a String to Hex?

I use this code to convert a String to a Hex value

public static String toHex(String arg) throws UnsupportedEncodingException {
return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}


The code seems to work fine but I don't understand the comment

/*YOUR_CHARSET?*/


What am I supposed to put there?

Answer

The code seems to work fine but I don't understand the comment /YOUR_CHARSET?/ ? Am I supposed to put there?

The method String#getBytes() converts a String into an array of bytes by encoding it using the platform's default charset. Calling String#getBytes() is risky as it makes your code dependent on the platform which could lead to decoding issues later if you change of platform, that is why it is highly encouraged to use String#getBytes(charset) instead in order to clearly specify the target charset this way it will work properly whatever the platform used assuming that the charset specified can cover properly all the characters of the String to encode. Indeed if you have for example accentuated characters in your String and you use a non matching charset like for example ASCII you will get decoding issues later.