1

これは、MIPS に移植する必要がある基数に応じて、整数を ASCII 文字列に変換する C 実装です。それを完全に行う前に、このコードがどのように機能するかを理解する必要があります (完全なコードは下部にあります)。

わからないこと:

何が

*p ++ = hexdigits[c]; 

正確に?p は char 配列のように見えるので、ここでどのような割り当てが行われているのかわかりません。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 に答える