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

来源:互联网 发布:随心所欲动作数据配布 编辑:程序博客网 时间:2024/06/11 12:27
写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。例如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;}

0 0
原创粉丝点击