貌似简单,实则不易,这是鄙人一个粗浅实现,应有更好之法!
1 bool binaryToHex(const char *inStr, char *outStr) 2 { 3 //asset。。。。。 4 static char hex[] = "0123456789ABCDEF"; 5 int len = strlen(inStr)/4; 6 int i = strlen(inStr)%4; 7 char current = 0; 8 if(i) 9 { 10 //如果二进制长度不是4的整数倍 11 while(i--) 12 { 13 current = (current << 1)|(*inStr - '0'); 14 inStr++; 15 } 16 *outStr = hex[current]; 17 ++outStr; 18 } 19 while(len--) //后续的长度为4的整数倍 20 { 21 current = 0; 22 for(i = 0; i < 4; ++i) 23 { 24 current = (current << 1)|(*inStr - '0'); 25 inStr++; 26 } 27 *outStr = hex[current]; 28 ++outStr; 29 } 30 *outStr = 0; //加结束符 31 return true; 32 }