编写一个函数itob(int n,char s[],int b),将整数n转换为以b进制的数。保存到s中

#include <stdio.h>

#include <assert.h>

#include <stdlib.h>

#include <string.h>


void swap(char *p1, char *p2)

{

char tmp = *p1;

*p1 = *p2;

*p2 = tmp;

}


void  reverse(char *pstart, char *pend)

{

assert((pstart != NULL) && (pend != NULL));

while (pstart < pend)

{

swap(pstart, pend);

pstart++;

pend--;

}

}


char *my_itob(int n, char s[], int b)

{

char *p = s;

assert(s != NULL);

if (s != NULL)

{

if (n < 0)

{

*s == '-';

n = n*(-1);

s++;

}

while (n)

{

*s = "0123456789abcdef"[n%b];

n /= b;

s++;

}

*s = '\0';

if (*p == '-')

reverse(p + 1, (p + strlen(p) - 1));

else

reverse(p, (p + strlen(p) - 1));

return p;

}

return NULL;

}



int main()

{

int num = 0;

scanf("%d", &num);

char output[20];

char *p = my_itob(num, output, 2);

printf("%s\n", p);

system("pause");

return 0;

}



你可能感兴趣的:(进制转换)