Click here to Skip to main content
15,310,056 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
int a=0;
 a = a*10 + str[i] - '0';

Why should '0' be subtracted from 'a*10+str[i]' to convert strings to integer?

What I have tried:

..............................
Posted
Updated 9-Dec-21 2:11am
Comments
CHill60 9-Dec-21 7:44am
   
Why not use the debugger to see what is happening and to work out why
Jahirul Sarker 9-Dec-21 14:13pm
   
I can understand it now. Thank you.
Richard MacCutchan 9-Dec-21 8:17am
   
If you subtract '0' from a numeric charactger, e.g. '3', it leaves the actual numeric value.

So '3' - '0' = 3

And, as suggested above, the debugger will show you how it works.
Jahirul Sarker 9-Dec-21 14:15pm
   
Yeah, I can understand it now.
'0' in ASCII = 48
'1' in ASCII = 49
so, 1-0 is equivalent to 49-48.
Thank you so much.

1 solution

Refer to ASCII table and you'll see that the '0' is decimal 48
   
Comments
CHill60 9-Dec-21 12:09pm
   
Might have been nicer to also point out that '3' is decimal 51 i.e. 51 - 48 = 3 :laugh:
Jahirul Sarker 9-Dec-21 14:16pm
   
Yes, now it's clear to me.
'0' in ASCII = 48
'1' in ASCII = 49
so, 1-0 is equivalent to 49-48.
Thank you
CHill60 9-Dec-21 14:17pm
   
My pleasure

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900