Thread: convert char array to integer number

  1. #1
    Embedded in C...
    Join Date
    Sep 2008
    Location
    Basingstoke, Hampshire
    Posts
    83

    convert char array to integer number

    Hello,

    I am attempting to convert a number from an array of chars into a reconstructed number. For example if I have an array:

    Code:
     char array[5] = {5,4,3,2,1};
    How can I convert it into
    Code:
     int converted = 54321;
    So far I have
    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        int lc_count;
        int tmp;
        int array_mult = 1;
        int hours_array[5] = {0,1,2,3,4};   // value is 1234
        int i = 4;
        
        for(lc_count = 0; lc_count <= 5; lc_count++)
        {
                     tmp = hours_array[i] * array_mult;
                     array_mult *= 10;
                     --i;
                     tmp += tmp;
        }
        
        printf("count value is:   %d" ,tmp);               
        
        system("PAUSE");    
        return 0;
    }
    but the output of printf is -200000, could anyone advise on what I may be doing incorrectly here?

    Thanks
    Dave

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    This statement is ineffective or meaningless:
    Code:
    tmp += tmp;
    because you reassign tmp at every iteration.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Embedded in C...
    Join Date
    Sep 2008
    Location
    Basingstoke, Hampshire
    Posts
    83
    Cheers, I can see that now. Retesting without that statement gives me -100000...

    What I actually want to do is take the calculated value of tmp and add it to the previous value, but I don't know how to code it.

    Mathematically it should be:
    Code:
    ([4]*1)+([3]*10)+([2]*100)+([1]*1000)+([0]*10000)

    --dave
    Last edited by droseman; 01-18-2010 at 10:15 AM. Reason: extra info

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Hmm. I would use a printf of all the relevent values inside the for loop to get a grip on how they are accumulating. Usually something like that is enough to find the flaw in yer logic.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    74
    since an array of chars is basically a string, why not try this...

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    int main (int argc, const char * argv[]) 
    {
    	int test = 0, intstr;
    	char str[6];
    
    	do {
    
    		printf("insert string -> ");
    		scanf("%s", str);
    
    		for (i=0; i<strlen(str); i++)
    			if (isalpha(str[i])) 
    				test++;	
    	} while (test != 0);
    	intstr = atoi(str);
    
    	return 0;
    }

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by budala
    since an array of chars is basically a string
    In a way, but a string with respect to the C standard is null terminated, whereas there is no requirement that an array of chars be null terminated, and indeed droseman gave such an example.

    Anyway, your main idea is just to use an existing function that does a conversion from a numeric string to a number, and in this I agree: one could simplify by ensuring null termination, and then use something like atoi(), or perhaps more robustly strtol().
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    Don't forget to check for overflows. It's probably a good idea to validate the char array as well so you don't end up doing operations with negative numbers.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <limits.h>
    
    int main(void)
    {
            int result = 0;
            const char arr[] = {5,4,3,2,1};
            const size_t num_elems = sizeof(arr) / sizeof(arr[0]);
            int mult = pow(10, num_elems - 1);
            size_t i;
    
            for (i = 0; i < num_elems; ++i)
            {
                    if (result > INT_MAX - arr[i] * mult)
                    {
                            fprintf(stderr, "%s\n", "Integer overflow");
                            return EXIT_FAILURE;
                    }
    
                    result += arr[i] * mult;
                    mult /= 10;
            }
    
            printf("Result: %d\n", result);
    
            return EXIT_SUCCESS;
    }

  8. #8
    Registered User
    Join Date
    Jan 2010
    Location
    Germany, Hannover
    Posts
    15
    there were just 2 errors in the orig. code, 1st the already mentioned summing up in the tmp var, second the obo ( off by one :-) error in the for loop:
    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
    
        int lc_count;
        int tmp=0;
        int array_mult = 1;
        int hours_array[5] = {0,1,2,3,4};   // value is 1234
        int i = 4;
        
        for(lc_count = 0; lc_count < 5; lc_count++) {
                     tmp = tmp + hours_array[i] * array_mult;
                     array_mult *= 10;
                     --i;
        }    
        printf("count value is:   %d \n" ,tmp);                   
        system("PAUSE");    
        return 0;
    }

  9. #9
    Embedded in C...
    Join Date
    Sep 2008
    Location
    Basingstoke, Hampshire
    Posts
    83
    Thank you very much kermitaner, that was exactly what I was after - have yourself a fine Hannovarian beer !

    To laserlight - thanks for pointing out those functions, I had not heard of those before.

    --dave

  10. #10
    Embedded in C...
    Join Date
    Sep 2008
    Location
    Basingstoke, Hampshire
    Posts
    83
    and as always, there is another complication...

    I have just realised that the array contains ASCII char values, which breaks this code, so I have tried this:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
    
        int lc_count;
        int tmp=0;
        int array_mult = 1;
        char hours_array[5] = {'1','5','9','7','4'};   // value is 1234
        int i = 4;
        
        for(lc_count = 0; lc_count < 5; lc_count++)
        {                 
                     hours_array[i] -= 0x30;
                     --i;
                     printf("%d\n\n", hours_array[i]);
        }
        
        for(lc_count = 0; lc_count < 5; lc_count++) {
                     tmp = tmp + hours_array[i] * array_mult;
                     array_mult *= 10;
                     --i;
        }    
        printf("count value is:   %d \n" ,tmp);                   
        system("PAUSE");    
        return 0;
    }
    the result from this is:

    Code:
    55
    
    57
    
    53
    
    49
    
    -1
    
    count value is:   -14111
    which is baffling considering the last time I looked 0x30 - 0x4 was not 0x55....

    --dave

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    char hours_array[5] = {'1','5','9','7','4'};   // value is 1234
    You don't really want to end up with 1234 out of this, do you?

    I was thinking of something like this:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
    
        int lc_count;
        int tmp2, tmp=0;
        int array_mult = 1;
        char array[5] = {'1','5','9','7','4'};   // value is 1234
        int i = 4;
        
    
        for(i = sizeof(array)-1, tmp2 = 0; i > -1; i--) {
          tmp2 = array[i] - '0';
          tmp2 *= array_mult;
          tmp = tmp + tmp2;
          array_mult *= 10;
        }    
        printf("count value is:   %d \n" ,tmp);                   
        system("PAUSE");    
        return 0;
    }
    Last edited by Adak; 01-19-2010 at 03:42 AM.

  12. #12
    Embedded in C...
    Join Date
    Sep 2008
    Location
    Basingstoke, Hampshire
    Posts
    83
    Thanks Adak, that was indeed what I was trying to do.

    Yes, I really should have removed that comment..

    Would it be possible to ask why you set up the for loop like that and what tmp2 does, please?

    --dave

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by droseman View Post
    Thanks Adak, that was indeed what I was trying to do.

    Yes, I really should have removed that comment..

    Would it be possible to ask why you set up the for loop like that and what tmp2 does, please?

    --dave
    Sure! Go ahead and ask!


    Just messing with ya!

    That's just the standard way to walk through an array, decrimenting. Tmp2 is just a placeholder. We need that value before we can start the next line of code. I suppose you could do something with parentheses, but the simpler your code logic is, (generally), the better.

  14. #14
    Embedded in C...
    Join Date
    Sep 2008
    Location
    Basingstoke, Hampshire
    Posts
    83
    Cheers for that.

    Is there any way this can get itself stuck in an infinite loop, since that is what has happened when I put it into my main (embedded) application.

    --dave

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Did you note that I changed the name of the array in my example?

    (I dislike long array names).

    Do you need to keep this char array as just char's and not add the end of string char to the end of it? Doing so would elevate it to a string, and then the standard string to number functions could be used.

    Post up your code that shows the endless loop, and I'll see what's up with it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. Issue w/ Guess My Number Program
    By mkylman in forum C++ Programming
    Replies: 5
    Last Post: 08-23-2007, 01:31 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM