[英]how does this algorithm work?
這是一個 C 實現,它根據我需要移植到 MIPS 的基數將 integer 轉換為 ASCII 字符串。 在我完全做到這一點之前,我需要了解這段代碼的工作原理(底部的完整代碼)並且我以前從未真正處理過純 C。
我不確定的是:
什么是
*p ++ = hexdigits[c];
到底做什么? 在我看來 p 是一個字符數組,所以我不確定這里進行的是什么賦值。 如果我能弄清楚 p 到底在做什么,我確定我能弄清楚 rest。謝謝!
#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++;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.