I’m currently reading the book “Beginning Android Games” and I have a problem understanding the following code:
int srcX = 0;
int srcWidth = 0;
if (ch == '.') {
srcX = 200; //Jump to position 200 px in the bitmap
srcWidth = 10; //A dot is only 10 px
} else {
srcX = (ch - '0') * 20;
srcWidth = 20;
}
I have a bitmap with numbers from 0 to 9 which is used to display high scores and the score while playing. The variable srcX is used to find the position (in pixels) in the bitmap for the corresponding number.
Ch is a character variable and is used to hold the current character in the string (which is either a number, a space or a dot).
My problem is that I don’t understand why we have to use (ch – ‘0’) in order to get the “real” number instead of the unicode number. For example, if ch = "1", (ch - '0') has the result of 1. If I don’t use “- ‘0’” I get the unicode, which is 49.
Of course, there has to happen something, in order to have a transformation from the unicode to the “real number”. But why results (ch – ‘0’) in 1 and not 49.
I hope you guys understand my problem and can help me.
Thanks in advance!
The character ‘0’ has the unicode (same as ASCII for values 0..127) value
48.‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’
have the char values
48, 49, .., 57
If you want to translate one of this characters to a value ( ‘0’ -> 0)
you can either do
or
which does both the same.