tags:

views:

105

answers:

3

How does this code concatenate the data from the string buffer? What is the * 10 doing? I know that by subtracting '0' you are subtracting the ASCII so turn into an integer.

char *buf; // assume that buf is assigned a value such as 01234567891234567
long key_num = 0;
someFunction(&key_num);
...

void someFunction(long *key_num) {

    for (int i = 0; i < 18; i++)
        *key_num = *key_num * 10 + (buf[i] - '0')
}

(Copied from my memory of code that I am working on recently)

+1  A: 

It just multiples the current long value (*key_num) by 10, adds the digit value, then stores the result again.

EDIT: It's not bit-shifting anything. It's just math. You can imagine it as shifting decimal digits, but it's binary internally.

key_num = 0 (0) 
key_num = key_num * 10 + ('0' - '0') (0)
key_num = key_num * 10 + ('1' - '0') (1)
key_num = key_num * 10 + ('2' - '0') (12)
Matthew Flaschen
can you explain further? Like how is it shifting to make room for the next digit?
yeungling
+3  A: 

As a shorter example with the number 1234, that can be thought of as:

1000 * 1 + 100 * 2 + 10 * 3 + 4

Or:

10 * (10 * (10 * 1 + 2) + 3) + 4

The first time through the loop, *key_num would be 1. The second time it is multiplied by 10 and 2 added (ie 12), the third time multiplied by 10 and 3 added (ie 123), the fourth time multiplied by 10 and 4 added (ie 1234).

Saxon Druce
+3  A: 

It's basically an atoi-type (or atol-type) function for creating an integral value from a string. Consider the string "123".

Before starting, key_num is set to zero.

  • On the first iteration, that's multiplied by 10 to give you 0, then it has the character value '1' added and '0' subtracted, effectively adding 1 to give 1.
  • On the second iteration, that's multiplied by 10 to give you 10, then it has the character value '2' added and '0' subtracted, effectively adding 2 to give 12.
  • On the third iteration, that's multiplied by 10 to give you 120, then it has the character value '3' added and '0' subtracted, effectively adding 3 to give 123.

Voila! There you have it, 123.

If you change the code to look like:

#include <iostream>

char buf[] = "012345678901234567";
void someFunction(long long *key_num) {
    std::cout << *key_num << std::endl;
    for (int i = 0; i < 18; i++) {
        *key_num = *key_num * 10 + (buf[i] - '0');
        std::cout << *key_num << std::endl;
    }
}

int main (void) {
    long long x = 0;
    someFunction (&x);
    return 0;
}

then you should see it in action (I had to change your value from the 17-character array you provided in your comment to an 18-character one, otherwise you'd get some problems when you tried to use the character beyond the end; I also had to change to a long long because my longs weren't big enough):

0
0
1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
1234567890123456
12345678901234567
paxdiablo