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)
It’s basically an
atoi-type (oratol-type) function for creating an integral value from a string. Consider the string"123".Before starting,
key_numis set to zero.'1'added and'0'subtracted, effectively adding 1 to give 1.'2'added and'0'subtracted, effectively adding 2 to give 12.'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:
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 longbecause my longs weren’t big enough):