2012-04-05 8 views
1

다음은 MIPS로 포팅해야하는 기수에 따라 정수를 ASCII 문자열로 변환하는 C 구현입니다. 내가 충분히 할 수 있기 전에,이 코드가 어떻게 작동하는지 (하단의 전체 코드)와 ive가 전에는 순수한 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] = "ABCDEF"; 

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

답변

7

이 :

*p ++ = hexdigits[c]; 

이 동일 :

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

또는 'P [0] = hexdigits [C] p ++; –

관련 문제