C语言实现字节流与十六进制字符串的相互转换

来源:互联网 发布:说说大数据的来源 编辑:程序博客网 时间:2024/05/16 06:59
 

C语言实现字节流与十六进制字符串的相互转换

 3430人阅读 评论(0) 收藏 举报
 分类:

原文出自:http://blog.csdn.net/qq387732471/article/details/7360988

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //字节流转换为十六进制字符串  
  2. void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen)  
  3. {  
  4.     short i;  
  5.     unsigned char highByte, lowByte;  
  6.   
  7.     for (i = 0; i < sourceLen; i++)  
  8.     {  
  9.         highByte = source[i] >> 4;  
  10.         lowByte = source[i] & 0x0f ;  
  11.   
  12.         highByte += 0x30;  
  13.   
  14.         if (highByte > 0x39)  
  15.                 dest[i * 2] = highByte + 0x07;  
  16.         else  
  17.                 dest[i * 2] = highByte;  
  18.   
  19.         lowByte += 0x30;  
  20.         if (lowByte > 0x39)  
  21.             dest[i * 2 + 1] = lowByte + 0x07;  
  22.         else  
  23.             dest[i * 2 + 1] = lowByte;  
  24.     }  
  25.     return ;  
  26. }  
  27.   
  28. //字节流转换为十六进制字符串的另一种实现方式  
  29. void Hex2Str( const char *sSrc,  char *sDest, int nSrcLen )  
  30. {  
  31.     int  i;  
  32.     char szTmp[3];  
  33.   
  34.     for( i = 0; i < nSrcLen; i++ )  
  35.     {  
  36.         sprintf( szTmp, "%02X", (unsigned char) sSrc[i] );  
  37.         memcpy( &sDest[i * 2], szTmp, 2 );  
  38.     }  
  39.     return ;  
  40. }  
  41.   
  42. //十六进制字符串转换为字节流  
  43. void HexStrToByte(const char* source, unsigned char* dest, int sourceLen)  
  44. {  
  45.     short i;  
  46.     unsigned char highByte, lowByte;  
  47.       
  48.     for (i = 0; i < sourceLen; i += 2)  
  49.     {  
  50.         highByte = toupper(source[i]);  
  51.         lowByte  = toupper(source[i + 1]);  
  52.   
  53.         if (highByte > 0x39)  
  54.             highByte -= 0x37;  
  55.         else  
  56.             highByte -= 0x30;  
  57.   
  58.         if (lowByte > 0x39)  
  59.             lowByte -= 0x37;  
  60.         else  
  61.             lowByte -= 0x30;  
  62.   
  63.         dest[i / 2] = (highByte << 4) | lowByte;  
  64.     }  
  65.     return ;  
  66. }  
0 0