想调优别人的代码,网上搜索一下Binary to Hexstring的转换,全是利用printf、scanf之类实现的,效率好低,还是自己想个简单的办法吧!

     .......此处省略一万字.......

改进后的方法:

 1 int tohex(void* str, int strlen, char *ascii, int size)
 2 {
 3     if(strlen == 0|| str== NULL || ascii==NULL)
 4     {
 5         if(NULL != ascii)
 6             ascii[0]=0x00;
 7         return 0;
 8     }
 9 
10      char* p1 = ascii;//new  char[len*2+1];
11     unsigned char* p2 = (unsigned char*)str;
12     int i = 0, j = 0;
13     char dict[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
14     bool blCuted = false;
15     for( i = 0; i < strlen; ++i)
16     {
17         p1[j] = dict[ (p2[i] >> 4)];
18         p1[j+1] = dict[p2[i] & 0x0F];
19         j+=2;
20 
21         if(j > size){
22             blCuted = true;
23             break;
24         }
25     }
26     if(blCuted)
27         j-=2 ;
28     p1[j]  =0x00;
29     return j;
30 }    

 

改进前的方法(抄的):

 1 int BCD2ASC(const char *str, int strlen,char *ascii, int size)
 2 {
 3     int    i = 0, p = 0, l = 0;
 4     byte ch;
 5 
 6     if(strlen == 0|| str== NULL || ascii==NULL)
 7         return NULL;
 8 
 9     bool blCuted = false;
10     while(i<strlen)
11     {
12         ch = str[i++];
13         l += 2;
14         if(l > size){
15             blCuted = true;
16             break;
17         }
18         p += sprintf(ascii+p, "%02X", ch);
19     }
20 
21     if(blCuted)
22         l-=2 ;
23     return l;
24 }
View Code

相关文章:

  • 2022-12-23
  • 2021-08-22
  • 2022-02-08
  • 2022-02-08
  • 2022-02-17
  • 2021-11-12
  • 2021-10-07
  • 2021-11-21
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案