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!

Share it:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • FriendFeed
  • StumbleUpon
  • Tumblr
  • Twitter
  • MySpace