Binary转换成Hex字符串

时间:2021-12-15 13:30:24

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

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

改进后的方法:

 int tohex(void* str, int strlen, char *ascii, int size)
{
if(strlen == || str== NULL || ascii==NULL)
{
if(NULL != ascii)
ascii[]=0x00;
return ;
} char* p1 = ascii;//new char[len*2+1];
unsigned char* p2 = (unsigned char*)str;
int i = , j = ;
char dict[]={'','','','','','','','','','','A','B','C','D','E','F'};
bool blCuted = false;
for( i = ; i < strlen; ++i)
{
p1[j] = dict[ (p2[i] >> )];
p1[j+] = dict[p2[i] & 0x0F];
j+=; if(j > size){
blCuted = true;
break;
}
}
if(blCuted)
j-= ;
p1[j] =0x00;
return j;
}

改进前的方法(抄的):

 int BCD2ASC(const char *str, int strlen,char *ascii, int size)
{
int i = , p = , l = ;
byte ch; if(strlen == || str== NULL || ascii==NULL)
return NULL; bool blCuted = false;
while(i<strlen)
{
ch = str[i++];
l += ;
if(l > size){
blCuted = true;
break;
}
p += sprintf(ascii+p, "%02X", ch);
} if(blCuted)
l-= ;
return l;
}

测试代码:

  int main( )
{
int a=0x1234;
int b=0xabcd;
char *bistr="\x12\x34\x56\x78\x90\xab\xcd\xef\xe1\xf9\x1f\x1e\x00";
char szTmp[*] = {};
tohex(&a, sizeof(int), szTmp, sizeof(szTmp)); cout << szTmp << endl;
tohex(&b, sizeof(int), szTmp, sizeof(szTmp)); cout << szTmp << endl;
tohex(bistr, strlen(bistr), szTmp, sizeof(szTmp)); cout << szTmp << endl; FILE* fp = fopen("D:\\testbinary.bi", "rb");
char szBinary[*] = {};
int ired = fread(szBinary, , *-, fp);
cout << "readlen:" << ired <<endl; DWORD dwB = GetTickCount();
for(int i = ; i < ; ++i)
{
tohex(szBinary, ired, szTmp, sizeof(szTmp)-); //i=1w,<200ms
cout << szTmp << endl;
BCD2ASC(szBinary, ired, szTmp, sizeof(szTmp)-); //i=1w,9000ms
cout << szTmp << endl;
}
DWORD dwE = GetTickCount(); cout << "cost:" << dwE-dwB << "ms" <<endl; fclose(fp);
return ;
}

效率差的不是一条街,你可以try一下。