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?
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.
Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings.
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.
You are casting an int (integer) ( 0 ) to a character (char). Casting means you are changing the type. Follow this answer to receive notifications.
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
Source: http://www.asciitable.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With