十进制数字串按要求转化为任意进制数字串(C语言描述)

题目描述:输入十进制数字串src(0~INT_MAX),和一个数字n(代表进制2~36),将src转化为n进制数字串返回。

输入:"10",2
输出:"1010"
输入:"10",15
输出:"A"
输入:"3275432",20
输出:"1098BC"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*enum 
{
	0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
	A, B, C, D, E, F, G, H, I, J,
	K, L, M, N, O, P, Q, R, S, T,
	U, V, W, X, Y, Z
};*/
char *base_convert(const char *Source, int n)
{
	if(Source == NULL || n < 2)
		return NULL;
	char *Destination = (char *) malloc(sizeof(char) * (32+1));
	//将源字符串转换成数字
	int srcLen = strlen(Source);
	int srcNum = 0;
	char scale[] = 	{	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
						'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
						'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
						'U', 'V', 'W', 'X', 'Y', 'Z'
					};
	for(int i=0; i<srcLen; i++)
	{
		srcNum *= 10;
		srcNum += Source[i] - '0';
	/*	if(srcNum > INT_MAX_SIZE || srcNum < INT_MIN_SIZE)
			return NULL;*/
	}
	int remainder = 0, i = 0;
	//按照短除法正取余数,并查找余数对应枚举类型,填入字符串
	while(srcNum>0 && i<=32)
	{
		remainder = srcNum % n;
		Destination[i++] = scale[remainder];
		srcNum /= n;
	}
	Destination[i--] = '\0';
	//返回逆序后新的进制字符串
	for(int j = 0; j < i; j++, i--)
	{
		int t = Destination[i];
		Destination[i] = Destination[j];
		Destination[j] = t;
	}
	return Destination;
}
int main()
{
	const char *str_from = "3275432";	//十进制数字串
	int n = 26;	//要转换的进制 
	char *str_to = NULL;
	str_to = base_convert(str_from, n);
	printf("%s",str_to);
	if(str_to != NULL)
	{
		free(str_to);
		str_to = NULL;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值