As you all know, ANSI C does not require implementations to use ASCII code points for the char
type. However it does define a basic character set with alphanumeric characters, whitespace characters and other printable characters. Are there library functions to portably convert a char
to its ASCII code and back?
Here are some functions to do the job, which return 0 if the character is not found; hopefully they are self-explanatory:
char const ascii_table[] = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
int char_to_ascii(int ch)
{
char const *p = strchr(ascii_table, ch);
return p ? p - ascii_table + 32 : 0;
}
int ascii_to_char(int a)
{
return (a >= 32 && a < 128) ? ascii_table[a-32] : 0;
}
Expanding this to cover 0-127 instead of 32-127 is left as an exercise to the reader 😉
Are there library functions to portably convert a char to its ASCII code and back?
There are no such functions in the standard library.
Hovewer, let's be realistic: It's very unlikely that your code will ever be used on a platform that doesn't use ASCII.
I would do this:
char char_to_ascii(char ch)
{
return ch;
}
char ascii_to_char(char ch)
{
return ch;
}
And then, if you need to compile the code for an exotic platform that doesn't use ASCII, you write proper implementations for those functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With