0

I have to read a string from a file and display the corresponding unicode representation in a Text field on my application.

For example I read the string "e13a" from the file and i'd like to display the corresponding "\ue13a" character in the Text field.

Is there a way to obtain the desired behaviour?

I already tried escaping the string directly in the file but I always obtain the raw string instead of the unicode representation

2 Answers2

3

tl;dr

Character.toString( Integer.parseInt( "e13a" , 16 ) ) 

See this code run at Ideone.com.

Code point

Parse your input string as a hexadecimal number, base 16. Convert to a decimal number, base 10.

That number represents a code point, the number permanently assigned to each of the over 144,000 characters defined in Unicode. Code points range from zero to just over one million, with most of that range unassigned.

String input = "e13a" ; 
int codePoint = Integer.parseInt( input , 16 ) ;

Instantiate a String object whose content is the character identified by that code point.

String output = Character.toString( codePoint ) ;

Avoid char

The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.

To work with individual characters, use code point integers as seen above.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Why answer this question when it is an obvious duplicate of [Creating Unicode character from its number](https://stackoverflow.com/q/5585919/2985643)? – skomisa Feb 07 '23 at 17:17
0

I posted the question after a lot of trying and searching. Shortly after posting I found a more trivial solution than I expected:

The converted string is:

String converted = String.valueOf((char) Integer.parseInt(unicodeString,16));

where "unicodeString" is the string I read from the file.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    This code fails with most characters. For example, the FACE WITH MEDICAL MASK emoji character, U+1F637, . See failure [at Ideone.com](https://ideone.com/pth4UU). – Basil Bourque Feb 07 '23 at 15:35