0

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.

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208

1 Answers1

2

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));
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Is there a better way that does not rely on char to int implicitly conversion ? – Ankur Agarwal Feb 04 '21 at 06:15
  • Are you implying that "relying on char to int implicit conversion" is somehow "worse" than not doing so. If you are, why? If you are not, what constitutes a "better" way? @AnkurAgarwal – Sweeper Feb 04 '21 at 06:18
  • 1
    @AnkurAgarwal not really, because just about *any* arithmetic you try to perform on the `char` (for instance, if you try to create a hex string manually using bit shifts and what-not) is going to implicitly convert the `char` anyway, typically to `int`. So, why wouldn't you want to just let Java do the work for you? – Remy Lebeau Feb 04 '21 at 21:41