[ create a new paste ] login | about

Link: http://codepad.org/mD7Y0sOC    [ raw code | output | fork ]

AaronMiller - C, pasted on Aug 30:
#line 2
#include <stdio.h>
#include <stdlib.h>

char *int_to_string(int n, int radix) {
    static const char const digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()[]{}<>_";
    static char buf[512];
    size_t i;
    int isneg;

    if (radix < 2 || radix > sizeof(digits)) {
        printf("...");
        return (char *)NULL;
    }

    isneg = 0;
    if (n < 0) {
        isneg = 1;
        n = -n;
    }

    i = sizeof(buf) - 1;
    buf[i--] = '\0';
    do {
        buf[i--] = digits[n%radix];
        n = n/radix;
    } while(n > 0);

    if (isneg)
        buf[i--] = '-';

    return &buf[i + 1];
}

void test_(unsigned int line, const char *sn, int n, int radix) {
    char *p;

    printf("[%u](%s; %i): ", line, sn, radix);

    p = int_to_string(n, radix);
    if (!p)
        printf("invalid parameter\n");
    else
        printf("%s\n", p);
    fflush(stdout);
}
#define test(n,radix) test_(__LINE__,#n,(n),(radix))

int main() {
    test(42, 10);
    test(23, 10);
    test(32, 16);
    test(0777, 8);
    test(0xFACEBEEF, 16);
    test(0x0B5E55ED, 16);
    test(1234, 10);
    test(20120830, 36);
    test(20121212, 36);
    test(0, 10);
    test(-43, 10);
    test(20121212, 47);
    test(20121212, 54);
    test(0xA, 2);

    return EXIT_SUCCESS;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[50](42; 10): 42
[51](23; 10): 23
[52](32; 16): 20
[53](0777; 8): 777
[54](0xFACEBEEF; 16): -5314111
[55](0x0B5E55ED; 16): B5E55ED
[56](1234; 10): 1234
[57](20120830; 36): BZ9BY
[58](20121212; 36): BZ9MK
[59](0; 10): 0
[60](-43; 10): -43
[61](20121212; 47): 45@Y&
[62](20121212; 54): 2J&F2
[63](0xA; 2): 1010


Create a new paste based on this one


Comments: