How to merge multiple numbers into one number like 4,0,0 into 400 without stdlib

Viewed 51

I'm trying to parse a file that has following data eg:

MAGICNUMBER 400

4 is = 0x34 0 is = 0x30

4 0 0 are different unsigned chars

what i want is those different chars to be converted into

unsigned int x = 400;

when parsing them into my program i want to merge them into one integer i tried bitshifting but it didn't work and i probably did it very wrong and got a very large number probably due misunderstanding of something, what i'm susposed to do to merge those numbers without string tricks and without using std but only using bitshift with a explanation how it works?

1 Answers

Each digit is c - '0'. When you get a new digit, you know that prior ones are one decimal place greater, so you multiply the current number by 10 and add the new digit:

char *s = "400";
int sum = 0;

while(*s >= '0' && *s <= '9') {
    sum = 10 * sum + (*s - '0');
    s++;
}
Related