how does this algorithm work?

Go To StackoverFlow.com

1

Here is a C implementation that converts an integer to an ASCII string depending on the radix which I need to port to MIPS. Before I can fully do that, I need to understand how this code works (full code at the bottom) and ive never really dealt with pure C before.

What im unsure of:

What does

*p ++ = hexdigits[c]; 

do exactly? It looks to me like p is a char array, so im unsure what assignment is going on here. If I can figure out what it is exactly that p is doing, im sure i can figure out the rest. Thanks!

#include    <stdio.h>
#include    <stdlib.h>

char    * my_itoa(unsigned int  v, char *p, int r)
{
    unsigned int c;
    char    *p_old, *q;
    static char   hexdigits[16] = "0123456789ABCDEF";

    if (r < 2 || r > 16) {
        *p = 0;
        return p;
    }

    if (v == 0) {
        *p = '0';
        return p;
    }

    p_old = p; 
hy
    // doing the conversion
    while (v > 0) {
        // You can get both c an v with ONE MIPS instruction 
        c = v % r;
        v = v / r;
        *p ++ = hexdigits[c]; 
    }

    *p = 0;

    // reverse the string

    // q points to the head and p points to the tail
    q = p_old;
    p = p - 1;

    while (q < p) {
        // swap *q and *p
        c = *q;
        *q = *p;
        *p = c;

        // increment q and decrement p
        q ++;
        p --;
    }

    return p_old;
}

char    buf[32];

int main (int argc, char **argv)
{
    int r;
    unsigned int m0 = (argc > 1) ? atoi(argv[1]) : 100;

    for (r = 2; r <= 16; r ++) 
        printf("r=%d\t%s\n", r, my_itoa(m0, buf, r));

    return 0;
}
2012-04-05 00:22
by jfisk


7

This:

*p ++ = hexdigits[c];

is identical to this:

*p = hexdigits[c];
p++;
2012-04-05 00:24
by Oliver Charlesworth
or p[0] = hexdigits[c]; p++;James McLaughlin 2012-04-05 00:25
Ads