C语言实现任意进制的转换,主要注意代码的小技巧

在Linux GCC编译测试通过,代码如下:

#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];
		value /= base;
	} while (ptr > buf && value);

	printf("base: %d, => %s \n", base, ptr);
}

转自:http://www.yinqisen.cn/blog-673.html

posted @ 2016-09-06 09:51  鹤骨松姿  阅读(2292)  评论(0编辑  收藏  举报