what does this do
while(*string) {
i = (i << 3) + (i<<1) + (*string -'0');
string++;
}
the *string -'0'
does it remove the character value or something?
what does this do
while(*string) {
i = (i << 3) + (i<<1) + (*string -'0');
string++;
}
the *string -'0'
does it remove the character value or something?
This subtracts from the character to which string
is pointing the ASCII code of the character '0'
. So, '0'
- '0'
gives you 0
and so on and '9'
- '0'
gives you 9
.
The entire loop is basically calculating "manually" the numerical value of the decimal integer in the string string
points to.
That's because i << 3
is equivalent to i * 8
and i << 1
is equivalent to i * 2
and (i << 3) + (i<<1)
is equivalent to i * 8 + i * 2
or i * 10
.
It converts the ascii value of 0-9 characters to its numerical value.
ASCII value of '0' (character) is 48 and '1' is 49. So to convert 48-56('0'-'9') to 0-9, you just need to subtract 48 from the ascii value. that is what your code line [ *string -'0' ] is doing.
Since the digits 0-9 are guaranteed to be stored contiguously in the character set, subtracting '0'
gives the integer value of whichever character digit you have.
Let's say you're using ASCII:
char digit = '6'; //value of 54 in ASCII
int actual = digit - '0'; //'0' is 48 in ASCII, therefore `actual` is 6.
No matter which values the digits have in the character set, since they're contiguous, subtracting the beginning ('0'
) from the digit will give the digit you're looking for. Note that the same is NOT particularly true for the letters. Look at EBCDIC, for example.