十六进制转换为十进制这样说有点笼统,因为一般来说十六进制是字符串,十进制也可能是字符串或是整数。下面我们来看看。
1.十六进制字符串转换为十进制的字符串
#include<stdio.h>
int main()
{
char str1[10]="32";//十六进制
char str2[10]={0};//十进制
sscanf(str1,"%02X",str2);
printf("str2=%s\n",str2);
return 0;
}
打印:str2=2
另一种方法:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int hexCharToValue(const char ch)//求字符串对应的偏移量
{
int result = 0;
if(ch >= '0' && ch <= '9')
{
result = (int)(ch - '0');
}
else if(ch >= 'a' && ch <= 'z'){
result = (int)(ch - 'a') + 10;
}
else if(ch >= 'A' && ch <= 'Z'){
result = (int)(ch - 'A') + 10;
}
else
{
result = -1;
}
return result;
}
int hexToStr(char *hex, char *ch)
{
int high,low;
int tmp = 0;
if(hex == NULL || ch == NULL)
{
return -1;
}
if(strlen(hex) %2 == 1)
{
return -2;
}
while(*hex){
high = hexCharToValue(*hex);//高位
if(high < 0)
{
*ch = '\0';
return -3;
}
hex++; //指针移动到下一个字符上
low = hexCharToValue(*hex);//地位
if(low < 0){
*ch = '\0';
return -3;
}
tmp = (high << 4) + low;
*ch++ = (char)tmp;
hex++;
}
*ch = '\0';
return 0;
}
int main(int argc, char *argv[])
{
char *p_hex = "32";//十六进制
char p_result[20] = {0};//十进制
hexToStr(p_hex, p_result);
printf("%s\n", p_result);
system("pause");
return 0;
}
打印:2
这两种方式都能解决问题,很明显第二种看起来复杂的多,但是实际用起来,第二种方法比第一种方法高效。实际工作中我解密的时候就碰到过这种情况,然后换了第二种方法。
2.十六进制字符串转换成十进制整形
#include<stdio.h>
int main()
{
char str1[10]="32";//十六进制
int a=0; //十进制
sscanf(str1,"%02X",&a);
printf("a=%d\n",a);
return 0;
}
打印:a=50
这个也可以用第二种方法,稍微变幻一下就行了。
十进制转十六进制用sprintf用的多,这个大家可以试一下。十六进制作为整数转十进制字符串到没怎么遇到过,十六进制整数转十进制数就不说了。主要还是sscanf效率低。
参考地址:
http://blog.csdn.net/stpeace/article/details/13168851
http://blog.chinaunix.net/uid-20680669-id-3157274.html