C語言實現字節流與十六進制字符串的相互轉換


轉自:http://blog.csdn.net/pingd/article/details/41945417/


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

[cpp] view plain copy
  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. }  

發佈了44 篇原創文章 · 獲贊 27 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章