C语言十六进制数据同字符串的相互转换

布满荆棘的人生 2022-05-12 04:50 322阅读 0赞
  1. //字节流转换为十六进制字符串
  2. void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen)
  3. {
  4. short i;
  5. unsigned char highByte, lowByte;
  6. for (i = 0; i < sourceLen; i++)
  7. {
  8. highByte = source[i] >> 4;
  9. lowByte = source[i] & 0x0f ;
  10. highByte += 0x30;
  11. if (highByte > 0x39)
  12. dest[i * 2] = highByte + 0x07;
  13. else
  14. dest[i * 2] = highByte;
  15. lowByte += 0x30;
  16. if (lowByte > 0x39)
  17. dest[i * 2 + 1] = lowByte + 0x07;
  18. else
  19. dest[i * 2 + 1] = lowByte;
  20. }
  21. return ;
  22. }
  23. //字节流转换为十六进制字符串的另一种实现方式
  24. void Hex2Str( const char *sSrc, char *sDest, int nSrcLen )
  25. {
  26. int i;
  27. char szTmp[3];
  28. for( i = 0; i < nSrcLen; i++ )
  29. {
  30. sprintf( szTmp, "%02X", (unsigned char) sSrc[i] );
  31. memcpy( &sDest[i * 2], szTmp, 2 );
  32. }
  33. return ;
  34. }
  35. //十六进制字符串转换为字节流
  36. void HexStrToByte(const char* source, unsigned char* dest, int sourceLen)
  37. {
  38. short i;
  39. unsigned char highByte, lowByte;
  40. for (i = 0; i < sourceLen; i += 2)
  41. {
  42. highByte = toupper(source[i]);
  43. lowByte = toupper(source[i + 1]);
  44. if (highByte > 0x39)
  45. highByte -= 0x37;
  46. else
  47. highByte -= 0x30;
  48. if (lowByte > 0x39)
  49. lowByte -= 0x37;
  50. else
  51. lowByte -= 0x30;
  52. dest[i / 2] = (highByte << 4) | lowByte;
  53. }
  54. return ;
  55. }

转至:https://blog.csdn.net/lee353086/article/details/5249161

发表评论

表情:
评论列表 (有 0 条评论,322人围观)

还没有评论,来说两句吧...

相关阅读