Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does string - '0' do (string is a char)

Tags:

c

string

char

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?

like image 376
Nabmeister Avatar asked Apr 17 '26 23:04

Nabmeister


1 Answers

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.

like image 172
Alexey Frunze Avatar answered Apr 20 '26 12:04

Alexey Frunze