十六进制转换为十进制的效率问题

                  十六进制转换为十进制这样说有点笼统,因为一般来说十六进制是字符串,十进制也可能是字符串或是整数。下面我们来看看。

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
 

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值