C/C++编程语言之进制转换16进制字符串转10进制字符串

写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。例如1:输入:0xA输出:10例如2:输入:0xB1输出:177
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*
功能:
    
输入:
    
输出:
     
返回:成功返回0,其它-1;
     
*/

int  favorite(int n)
{
	int i;
	long total = 1;
	if(n >= 1)
	{
		for(i=0 ; i<n; i++)
		{
			total *= 16;
		}
	}
	return total;
}

int  hex2num(char ch)
{
	int value = 0;
	if(ch >= '0' &&  ch < '9')
	{
		value = ch -48;
	}
	if(ch >= 'A' && ch<= 'F')
	{
		value = ch - 65 + 10;
	}
	if(ch >= 'a' && ch<= 'f')
	{
		value = ch - 97 + 10;
	}
	return  value;
}
int GetValue( char* strInValue,char* strOutValue )
{
	char*  p = strInValue;
	if(*p != '0' ||  *(p+1) != 'X')
		return -1;
	p+=2;
	char hex[9];
	char str[9];
	int  cnt=0,i=0;
	int  sum=0;
	while(*p != '\0')
	{
		hex[cnt++] = *p;
		p++;
	}
	hex[cnt] = '\0';
	for(i=0;i<cnt;i++)
	{
		str[i] = hex[cnt-1-i];
	}
	str[cnt] = '\0';
	for(i = 0; i < cnt; i++)
	{
		sum += favorite(i)*hex2num(str[i]);
	}
	itoa(sum, strOutValue, 10);

	return  0;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值