If you have Java 5, use char c = ...; String s = String.format ("\\u%04x", (int)c); char c = ...; String s = String.format ("\\u%04x", (int)c);
If your source is not a Unicode character ( char ), but a string, you must use charAt(index) to get the Unicode character at the index position.
Do not use codePointAt(index) because this will return 24-bit values โโ(full Unicode) that cannot be represented by only four hexadecimal digits (it needs 6). See docs for explanation .
[EDIT] To make this clear: this answer does not use Unicode, but a method that uses Java to represent Unicode characters (ie surrogate pairs), since char is 16 bits and Unicode is 24 bits. The question should be: "How to convert char to a 4-digit hexadecimal number", since it (really) does not apply to Unicode.
Aaron Digulla Feb 08 '10 at 9:13 2010-02-08 09:13
source share