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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM