《c程序设计语言》读书笔记-3.5-按要求进制位数字转字符串

#include <io.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

void reverse(char s[])
{
    int c,i,j;

    for(i = 0,j = strlen(s) - 1;i < j;i++,j--)
        c = s[i],s[i] = s[j],s[j] = c;
}

void itoa(int n,char s[],int b)
{
    int i,sign,j;

    sign = n,i = 0;

    do
    {
        j =  abs(n % b);
        s[i++] = (j <= 9) ? j + '0' : j - 10 + 'a';
    }while((n /= b) != 0);

    if(sign < 0)
        s[i++] = '-';
        s[i] = '\0';
        reverse(s);
}

int main()
{
    int n,i,b;
    char s[50];
    n = -165;
    b = 16;

    itoa(n,s,b);

    for(i = 0;i < strlen(s);i++)
        printf("%c  ",s[i]);


	return 0;
}


posted @ 2014-11-11 11:20  司空格子Ored  阅读(187)  评论(0编辑  收藏  举报