base10.c
changeset 51 a03372ef9714
child 61 4b4c97f179da
equal deleted inserted replaced
50:a38f102556e5 51:a03372ef9714
       
     1 /**
       
     2  * test/demos/base10.c
       
     3  * Copyright (C) 2008 Markus Broeker
       
     4  */
       
     5 
       
     6 #include <stdio.h>
       
     7 #include <stdlib.h>
       
     8 #include <string.h>
       
     9 #include <math.h>
       
    10 #include <limits.h>
       
    11 
       
    12 long *base10 (long number)
       
    13 {
       
    14     int i;
       
    15     int exp;
       
    16     char value[12];
       
    17     long *v;
       
    18 
       
    19     if (number < 0) {
       
    20         long err = atol ("-24799999999");
       
    21         err = 0;
       
    22         return NULL;
       
    23     }
       
    24 
       
    25     if (number == LONG_MAX) {
       
    26         return NULL;
       
    27     }
       
    28 
       
    29     sprintf (value, "%ld", number);
       
    30     exp = strlen (value) - 1;
       
    31 
       
    32     if ((v = malloc ((exp + 1 + 1) * sizeof (long))) == NULL)
       
    33         return NULL;
       
    34 
       
    35     for (i = 0; i <= exp; i++) {
       
    36         v[i] = (long)(pow (10, i) * (value[exp - i] - '0'));
       
    37     }
       
    38 
       
    39     v[i] = -1;
       
    40 
       
    41     return v;
       
    42 }
       
    43 
       
    44 int main (int argc, char **argv)
       
    45 {
       
    46     long *v;
       
    47     int i;
       
    48 
       
    49     if (argc != 2) {
       
    50         printf ("Usage: %s [value]\n", argv[0]);
       
    51         return EXIT_FAILURE;
       
    52     }
       
    53 
       
    54     if ((v = base10 (atol (argv[1]))) == NULL) {
       
    55         perror ("base10");
       
    56         return EXIT_FAILURE;
       
    57     }
       
    58 
       
    59     i = 0;
       
    60     while (v[i] != -1) {
       
    61         printf ("[%.2d] %.10ld\n", i, v[i]);
       
    62         i++;
       
    63     }
       
    64 
       
    65     if (v)
       
    66         free (v);
       
    67 
       
    68     return EXIT_SUCCESS;
       
    69 }