Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

c++ - Why does subtracting '0' in C result in the number that the char is representing?

Can someone explain why this works?

char c = '9';
int x = (int)(c - '0');

Why does subtracting '0' from an ascii code of a char result the number that that char is representing?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because the char are all represented by a number and '0' is the first of them all.

On the table below you see that:

'0' => 48
'1' => 49


'9' => 57.

As a result: ('9' - '0') = (57 ? 48) = 9

enter image description here Source: http://www.asciitable.com


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...