6

I have a String representing the hex value of a char, such as: "0x6d4b". How can I get the character it represents as a char?

String c = "0x6d4b";
char m = ???
Miquel
  • 15,405
  • 8
  • 54
  • 87

4 Answers4

9
// Drop "0x" in order to parse
String c = "6d4b";
// Parse hexadecimal integer
int i = Integer.parseInt( c, 16 );
// Note that this method returns char[]
char[] cs = Character.toChars( i );
// Prints 测
System.out.println( cs );
Gustav Barkefors
  • 5,016
  • 26
  • 30
  • 1
    are you sure it's not just ``(char)i``? – Hachi Jun 27 '12 at 07:58
  • Yes, if the resulting value is used as a `char`, the results are the same. The method call gives you the added bonus of readily available javadoc that tells what you're actually getting. – Gustav Barkefors Jun 27 '12 at 08:08
2
String s = "6d4b";
int i = Integer.parseInt( s, 16 );   // to convert hex to integer
char ca= (char) i;
System.out.println(ca);
Fathah Rehman P
  • 8,401
  • 4
  • 40
  • 42
0
System.out.println((char)Integer.parseInt("6d4b",16));
David
  • 15,894
  • 22
  • 55
  • 66
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
-1

Try this,

String s ="0x6d4b" ;
        char[] c = s.toCharArray();

        for (char cc : c){

            System.out.print(cc);
        }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75