Convert char to int

Nov 23, 2014 at 4:56am
I have googled this basic problem and find this solotion fastest:


1
2
  char a = '4';
  int ia = a - '0';


Does the phrase "" a - '0' " have a particular meaning or it's just a syntax in C++? I mean how can it work?
Last edited on Nov 23, 2014 at 4:57am
Nov 23, 2014 at 5:13am
If you look at an ascii table '0' starts at 48 and '9' ends at 57. So in this case '4' is equal to 52 so 52 - 48 = 4.
Nov 23, 2014 at 5:16am
Yes it subtracts the ASCII value of 0 from a. ia therefore contains the numerical value of a when it is indeed a number ('0 to '9', single digit)

http://www.asciitable.com
Last edited on Nov 23, 2014 at 5:17am
Nov 23, 2014 at 5:16am
The reason it works is because a char is a number. The most common form is that a char stores the ASCII or UTF-8 value for the character, and '4' would be translated into that value (e.g. 52).

In general, you would expect that the numbers would be in order, i.e. 0123456789. So, if you subtract the character with the value for '0' (e.g. 48), you should get the difference in position.

In your example:
1
2
char a = '4';      // a  = 52
int ia = a - '0';  // ia = 52 - 48 = 4 
Nov 23, 2014 at 8:47am
Got it. Thank you very much.
Topic archived. No new replies allowed.