int to string by specified base

int to string by specified base

 

convert a int to string, by specified base, support 2 - 16,

 

code:

#include <stdio.h>

/*
 * @author kuchaguangjie
 * @date 2012-04-03 22:10
 * @mail kuchaguangjie@gmail.com
 */
 
/**
 * convert int to string of specified base,
 * @param n
 	input number
 * @param s
 	output string
 * @param base
 		the base, between [2 - 16]
 * @param maxwidth
 	the possible max width after convertion
 * @ return
 	0 means ok, -1 means has problem
 */
int itob_base(int n, char *s, int base, int maxwidth) {
	if(base>16 ||  base<2) {
		printf("base should between 2~16\n");
		return -1;
	}
	int quotients[maxwidth], bc=0, i;
	while(n>=base) {
		quotients[bc++] = n % base;
		n /= base;
	}
	quotients[bc] = n;
	for(i=0;bc>=0;i++,bc--) {
		if(quotients[bc]<10) {
			s[i] = quotients[bc] + '0';
		} else if(quotients[bc]<16) {
			s[i] = quotients[bc] + 'A' - 10;
		}
	}
	s[i] = '\0';
	return 0;
}

/**
 * convert int to string of specified base, the possible max width is 32,
 * @param n
 	input number
 * @param s
 	output string
 * @param base
 		the base, between [2 - 16]
 */
int itob(int n, char *s, int base) {
	return itob_base(n, s, base, 32);
}

main() {
	char s[33];
	int n = 1000, base = 16;
	itob(n, s, base);
	printf("%s\n",s);
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值