Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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++;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading