Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ASCII code of C `char` portably in ANSI C

Tags:

c

ascii

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?

like image 320
ThePiercingPrince Avatar asked Dec 22 '22 21:12

ThePiercingPrince


2 Answers

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 😉

like image 144
M.M Avatar answered Dec 25 '22 09:12

M.M


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.

like image 39
HolyBlackCat Avatar answered Dec 25 '22 10:12

HolyBlackCat