1

这是一个 C 实现,它根据我需要移植到 MIPS 的基数将整数转换为 ASCII 字符串。在我完全做到这一点之前,我需要了解这段代码是如何工作的(底部的完整代码),而且我以前从未真正处理过纯 C。

我不确定:

做什么

*p ++ = hexdigits[c]; 

究竟是做什么的?在我看来 p 是一个字符数组,所以我不确定这里发生了什么分配。如果我能弄清楚 p 到底在做什么,我相信我能弄清楚其余的。谢谢!

#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;
}
4

1 回答 1

7

这个:

*p ++ = hexdigits[c];

与此相同:

*p = hexdigits[c];
p++;
于 2012-04-05T00:24:50.363 回答