admin 管理员组文章数量: 887017
Binary转换成Hex字符串
想调优别人的代码,网上搜索一下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
测试代码:
1 int main( ) 2 { 3 int a=0x1234; 4 int b=0xabcd; 5 char *bistr="\x12\x34\x56\x78\x90\xab\xcd\xef\xe1\xf9\x1f\x1e\x00"; 6 char szTmp[1024*10] = {0}; 7 tohex(&a, sizeof(int), szTmp, sizeof(szTmp)); cout << szTmp << endl; 8 tohex(&b, sizeof(int), szTmp, sizeof(szTmp)); cout << szTmp << endl; 9 tohex(bistr, strlen(bistr), szTmp, sizeof(szTmp)); cout << szTmp << endl; 10 11 FILE* fp = fopen("D:\\testbinary.bi", "rb"); 12 char szBinary[1024*5] = {0}; 13 int ired = fread(szBinary, 1, 1024*5-1, fp); 14 cout << "readlen:" << ired <<endl; 15 16 DWORD dwB = GetTickCount(); 17 for(int i = 0; i < 1; ++i) 18 { 19 tohex(szBinary, ired, szTmp, sizeof(szTmp)-1024); //i=1w,<200ms 20 cout << szTmp << endl; 21 BCD2ASC(szBinary, ired, szTmp, sizeof(szTmp)-1024); //i=1w,9000ms 22 cout << szTmp << endl; 23 } 24 DWORD dwE = GetTickCount(); 25 26 cout << "cost:" << dwE-dwB << "ms" <<endl; 27 28 fclose(fp); 29 return 0; 30 }View Code
效率差的不是一条街,你可以try一下。
转载于:.html
本文标签: Binary转换成Hex字符串
版权声明:本文标题:Binary转换成Hex字符串 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1732353611h1533804.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论