# In Asymptote, how can I convert a hex code to its corresponding ascii character?

In `Asymptote`, I want to convert a hex code into a string containing the corresponding ascii character. For example, given "4E", I want a code that returns "N".

There is a built-in function `int hex(string s)` that will convert from hex to decimal, so a function that will convert an int to an ascii character will also solve my problem.

There is a built-in function `int ascii(string s)` that does the reverse of what I am looking for. So `ascii("N")` will return an integer of value 78 (equivalent to a hex code of "4E").

Finally, I know that it is possible to convert a hex code to a character directly using single quotes as follows `string str = '\x4E';`. This doesn't help me because I have the string "4E" already defined in a string variable.

Here are the commands discussed above and their associated outputs. I want a function with the string `hexCode` as the input and the string "N" as the output.

``````string hexCode = "4E";
write('\x4E');           // -----> N
write(hex(hexCode));     // -----> 78
write(ascii("N"));       // -----> 78
write('\x' + hexCode);   // -----> \x4E
write("\x4E");           // -----> \x4E
``````

You can use C-style format strings:

``````string hexCode = "4E";
write('\x4E');                    // -----> N
write(hex(hexCode));              // -----> 78
write(ascii("N"));                // -----> 78
write('\x' + hexCode);            // -----> \x4E
write("\x4E");                    // -----> \x4E
write(format("%c",hex(hexCode))); // -----> N
``````

See for example https://en.cppreference.com/w/c/io/fprintf for a list of conversion codes, `%c` means int to character.

• Awesome. Thanks! Dec 22, 2021 at 21:49