函数 char *digitToAlpha (int val, char *buf, unsigned radix) 的功能是将数值转换为字符串。
参数:第一个是要转化的整数,第二个是转化后的字符串,第三个是要转化整数的基数,就是说如果基数是10,就可以直接转化,如果不是10,是其他值(2-36之间),则先把该整数转化为该基数的数后,再转化为字符串。
01 |
#include <stdio.h> |
02 |
#include <stdlib.h> |
03 |
char *digitToAlpha ( int val, char *buf, unsigned radix); |
04 |
int main( int argc, char *argv[]) |
05 |
{ |
06 |
int iNum = 55; |
07 |
char strNum[10] = "" ; |
08 |
digitToAlpha(iNum,strNum,10); |
09 |
printf ( "%s \n" ,strNum); |
10 |
|
11 |
system ( "PAUSE" ); |
12 |
return 0; |
13 |
} |
14 |
/* |
15 |
功能:将数值转换为字符串 |
16 |
参数:第一个是要转化的整数 |
17 |
第二个是转化后的字符串 |
18 |
第三个是要转化整数的基数,就是说如果基数是10,就可以直接转化,如果不是10,是其他值(2-36之间),则先把该整数转化为该基数的数后,再转化为字符串 |
19 |
*/ |
20 |
char *digitToAlpha ( int val, char *buf, unsigned radix) |
21 |
{ |
22 |
char *p; /* pointer to traverse string */ |
23 |
char *firstdig; /* pointer to first digit */ |
24 |
char temp; /* temp char */ |
25 |
unsigned digval; /* value of digit */ |
26 |
p = buf; |
27 |
if (val<0) |
28 |
{ |
29 |
/* negative, so output '-' and negate */ |
30 |
*p++= '-' ; |
31 |
val = (unsigned long )(-( long )val); |
32 |
} |
33 |
firstdig = p; /* save pointer to first digit */ |
34 |
do { |
35 |
digval = (unsigned)(val%radix); |
36 |
val /=radix; /* get next digit */ |
37 |
/* convert to ascii and store */ |
38 |
if (digval > 9) |
39 |
*p++ = ( char ) (digval - 10 + 'a' ); /* a letter */ |
40 |
else |
41 |
*p++ = ( char ) (digval + '0' ); /* a digit */ |
42 |
} while (val > 0); |
43 |
/* We now have the digit of the number in the buffer, but in reverse |
44 |
order. Thus we reverse them now. */ |
45 |
*p-- = '\0' ; /* terminate string; p points to last digit */ |
46 |
do |
47 |
{ |
48 |
temp = *p; |
49 |
*p =*firstdig; |
50 |
*firstdig= temp; /* swap *p and *firstdig */ |
51 |
--p; |
52 |
++firstdig; /* advance to next two digits */ |
53 |
} while (firstdig < p); /* repeat until halfway */ |
54 |
return buf; |
55 |
} |
转载随意,但请带上本文地址: