javaunicodesurrogate-pairs

How to print surrogate chars as ints in Java


I have this:

char c = "\ud804\udef4".charAt(0);
char d = "\ud804\udef4".charAt(1);

How will I print c and d as hex Strings ?

I want d804 for c and def4 for d.


Solution

  • It doesn't matter whether the char is a surrogate pair or not. If you have a char, you can convert it to a hex string by Integer.toHexString(), since chars can be implicitly converted to int.

    System.out.println(Integer.toHexString(c));
    System.out.println(Integer.toHexString(d));