Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

digits

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?

like image 869
Silviu. Avatar asked Mar 24 '13 12:03

Silviu.


People also ask

What happens when you subtract a char from a char?

And as it turns out, when you do "character math", subtracting any alphabetical character from any other alphabetical character (of the same case) results in bits being flipped in such a way that, if you were to interpret them as an int , would represent the distance between these characters.

Can you subtract chars in C?

Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings.

How does the -' 0 and +' 0 work in C?

These are character (integer values) so the + or - '0' will subtract the ascii value from the left side of the expression. If you are talking about a zero and not a capital Oh, that has a decimal value of 48, so you are subtracting or adding 48.

What is the meaning of char -' 0?

You are casting an int (integer) ( 0 ) to a character (char). Casting means you are changing the type. Follow this answer to receive notifications.


1 Answers

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 hereSource: http://www.asciitable.com

like image 89
Jean Avatar answered Oct 02 '22 21:10

Jean