Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hexadecimal unicode character into its visual representation

Tags:

c#

char

hex

unicode

I am trying to make a C# program that translates unicode character from its hexadecimal format to a single character, and I have a problem. This is my code:

This works:

char e = Convert.ToChar("\u0066"); 

However, this doesn't work:

Console.WriteLine("enter unicode format character (for example \\u0066)");
string s = Console.ReadLine();
Console.WriteLine("you entered (for example f)");
char c = Convert.ToChar(s); 

Because (Convert.ToChar("\\u0066")) gives the error:

String must be exactly one character long

Anyone have an idea how to do this?

like image 296
vldmrrdjcc Avatar asked Jul 03 '11 17:07

vldmrrdjcc


People also ask

How do you write hexadecimal Unicode?

To insert a Unicode character, type the character code, press ALT, and then press X. For example, to type a dollar symbol ($), type 0024, press ALT, and then press X. For more Unicode character codes, see Unicode character code charts by script.

How do I write Unicode in Word?

Inserting Unicode CharactersType the character code where you want to insert the Unicode symbol. Press ALT+X to convert the code to the symbol. If you're placing your Unicode character immediately after another character, select just the code before pressing ALT+X.

How do I use Unicode in Word for Mac?

On your standard Mac keyboard, just type Option and the Unicode number for the character, and the character is applied to whatever text field you're currently typing in. As an example, Mac keyboards have special symbols that indicate Control, Option, and Command (Cmd).


1 Answers

int.Parse doesn't like the "\u" prefix, but if you validate first to ensure that it's there, you can use

char c = (char)int.Parse(s.Substring(2), NumberStyles.HexNumber);

This strips the first two characters from the input string and parses the remaining text.

In order to ensure that the sequence is a valid one, try this:

Regex reg = new Regex(@"^\\u([0-9A-Fa-f]{4})$");
if( reg.IsMatch(s) )
{
  char c = (char)int.Parse(s.Substring(2), NumberStyles.HexNumber);
}
else
{
  // Error
}
like image 127
Steve Morgan Avatar answered Sep 17 '22 01:09

Steve Morgan