c++ 16进制转化为10进制的几种方法

 第一种方法:

    

[cpp]  view plain copy
  1. int hex_char_value(char c)     
  2. {     
  3.     if(c >= '0' && c <= '9')     
  4.         return c - '0';     
  5.     else if(c >= 'a' && c <= 'f')     
  6.         return (c - 'a' + 10);     
  7.     else if(c >= 'A' && c <= 'F')     
  8.         return (c - 'A' + 10);     
  9.     assert(0);     
  10.     return 0;     
  11. }     
  12. int hex_to_decimal(const char* szHex, int len)     
  13. {     
  14.     int result = 0;     
  15.     for(int i = 0; i < len; i++)     
  16.     {     
  17.         result += (int)pow((float)16, (int)len-i-1) * hex_char_value(szHex[i]);     
  18.     }     
  19.     return result;     
  20. }    
  

 

 第二种方法:

 int x;

sscanf("abc", "%x", x);

 

  第三种方法:

 

[cpp]  view plain copy
  1. static int hex_table[]={0,0,0,0,0,0,0,0,0,  
  2.                         0,0,0,0,0,0,0,0,0,  
  3.                         0,0,0,0,0,0,0,0,0,  
  4.                         0,0,0,0,0,0,0,0,0,  
  5.                         0,0,0,0,0,0,0,0,0,  
  6.                         0,0,0,0,1,2,3,4,5,6,  
  7.                         7,8,9,0,0,0,0,0,0,  
  8.                         0,10,11,12,13,14,15,0,0,  
  9.                         0,0,0,0,0,0,0,0,0,  
  10.                         0,0,0,0,0,0,0,0,0,  
  11.                         0,0,0,0,0,0,10,  
  12.                         11,12,13,14,15};   
  13. int hex_to_decimal(char* hex_str)   
  14. {  
  15.     char ch;   
  16.     int iret=0;  
  17.     while(ch=*hex_str++)   
  18.     {   
  19.         iret=(iret<<4)|hex_table[ch];  
  20.     }   
  21.     return iret;   
  22. }  

 

最后一个方法 是通过 建立一个表,直接将十六进制字符作为索引来得到值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值