C语言实现任意进制的转换,主要注意代码的小技巧
在Linux GCC编译测试通过,代码如下:
~~~.c
#include <stdio.h>
void tobase(int, int);
int main()
{
tobase(33, 16);
return 0;
}
void tobase(int value, int base)
{
static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char buf[(sizeof(long) << 3) + 1];
char *ptr, *end;
if (base < 2 || base > 36) {
printf("error base range \n");
}
end = ptr = buf + sizeof(buf) - 1;
*ptr = '\0';
do {
*--ptr = digits;
value /= base;
} while (ptr > buf && value);
printf("base: %d, => %s \n", base, ptr);
}
~~~
这只是“形式”上的转换吧,输入整形变量,输出字符串。
代码风格不算好,现在早已不是80x25终端机时代了,何必吝啬分行定义变量、赋值呢? lz这是干TM啥呢?搬来搬去有什么意义吗?
页:
[1]