Char to Int Conversion in C
filed in Teknik on Jul.02, 2010
The programming thing has a lot of tricks and as a programmer, I like them very very much.
The latest trick that i have come across is converting a char digit to its integer value.
As you know, if you write something like this:
char num[11] = "0123456789";
int s = (int)num[0];
printf("%d\n",s);
It will not print 0, but instead it will print the ASCII value of ’0′.
While looking for a quick solution, I have seen this perfect trick at stackoverflow:
char num[11] = "0123456789";
int s = num[0] - '0';
printf("%d\n",s);
Since all the digits are consecutive at the ASCII Table, -supposing all the elements are digits- substracting the ASCII value of ’0′ from that digit’s ASCII value gives you the correct integer value of the digit.
All that I can say is: FASCINATING!
July 2nd, 2010 on 10:27
I prefer atoi for converting char arrays to integer but it is also good for single characters.
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/