Use a Decimal Value as a Hexadecimal Value

I have the int 15 (or the string "15", that's just as easy), and I need to use it to create the value:

"\u0015"

Is there some conversion which would accomplish this? I can't do this:

"\u00" + myInt.ToString()

Because the first literal is invalid. Is there a simple way to get this result?

(If you're curious, this is for integrating with a hardware device where the vendor sometimes expresses integer values as hexadecimal. For example, I'd need to send today's date to the device as "\u0015\u0010\u0002".)

Jon Skeet
people
quotationmark

Given that you want a Unicode code point of 21, not 15, you should definitely start with the string "15". If you try to start with 15 as an int, you'll find you can't express anything with a hex representation involving A-F...

So, given "15" the simplest way of parsing that as hex is probably:

string text = "15";
int codePoint = Convert.ToInt32(text, 16);

After that, you just need to cast to char:

string text = "15";
int codePoint = Convert.ToInt32(text, 16);
char character = (char) codePoint;

Note that this will only work for code points in the Basic Multilingual Plane (BMP) - i.e. U+0000 to U+FFFF. If you need to handle values beyond that (e.g. U+1F601) then you should use char.ConvertFromUtf32 instead:

string text = "15";
int codePoint = Convert.ToInt32(text, 16);
string character = char.ConvertFromUtf32(codePoint);

people

See more on this question at Stackoverflow