Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Char to its unicode hexadecimal string representation and vice-versa

I need to generate the hexadecimal code of Java characters into strings, and parse those strings again later. I found here that parsing can be performed as following:

char c = "\u041f".toCharArray()[0];

I was hoping for something more elegant like Integer.valueOf() for parsing.

How about generating the hexadecimal unicode properly?

like image 423
Jérôme Verstrynge Avatar asked May 27 '13 09:05

Jérôme Verstrynge


People also ask

Can Java strings handle Unicode character strings?

Internally in Java all strings are kept in Unicode. Since not all text received from users or the outside world is in unicode, your application may have to convert from non-unicode to unicode.

How do you convert a string with Unicode encoding to a string of letters?

String str1 = "\u0000"; String str2 = "\uFFFF"; String str1 is assigned \u0000 which is the lowest value in Unicode. String str2 is assigned \uFFFF which is the highest value in Unicode.

How do you escape Unicode characters in Java?

According to section 3.3 of the Java Language Specification (JLS) a unicode escape consists of a backslash character (\) followed by one or more 'u' characters and four hexadecimal digits. So for example \u000A will be treated as a line feed.

What is uFFFF article referred to in Java?

\uFFFF is a format of how Unicode is presented in where I read it from (say ASCII file), not a literal.


1 Answers

This will generate a hex string representation of the char:

char ch = 'ö';
String hex = String.format("%04x", (int) ch);

And this will convert the hex string back into a char:

int hexToInt = Integer.parseInt(hex, 16);
char intToChar = (char)hexToInt;
like image 106
noel Avatar answered Sep 29 '22 12:09

noel