c - 这个算法是如何工作的?

标签 c

这是一个 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;
}

最佳答案

这个:

*p ++ = hexdigits[c];

与此相同:

*p = hexdigits[c];
p++;

关于c - 这个算法是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10021110/

相关文章:

java - 在 O(n) 中查找数组中的所有差异

c - C中三元运算符的逻辑?

C : Input file does not sort in array

c++ - 在 Makefile.am 的 _SOURCE 中分配 c 和 cpp 文件

c++ - 在 OpenGL 中绘制形状的标准(常见)方法是什么?

c - 段错误(核心转储)...BMH 算法

c++ - 以编程方式列出字符设备

c - 划分数组并从每个 block 中减去数组元素 : C program

c - UVA Judge 上的运行时错误和 codechef 上同一问题的错误答案

c - 如何在 C 中找到行指针?