十进制数字串按要求转化为任意进制数字串(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; isrcLen; i++)
	{
		srcNum *= 10;
		srcNum += Source[i] - '0';
	/*	if(srcNum  INT_MAX_SIZE || srcNum  INT_MIN_SIZE)
			return NULL;*/
	}
	int remainder = 0, i = 0;
	//按照短除法正取余数,并查找余数对应枚举类型,填入字符串
	while(srcNum0  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;
}
最新回复(0)
/jishuYeudpUgqdmoXt1_2BGVhEJ3L2wSelbFTrm1vuZKB11yCw_3D4795351
8 简首页