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

青旅半醒 2022-05-19 05:15 310阅读 0赞

在调试串口经常碰到需要把读出来的hex data转化成string类型输出,记录下来

//字节流转换为十六进制字符串
//itoa,16进制变字符串,1字节变两字节

  1. void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen)
  2. {
  3. short i;
  4. unsigned char highByte, lowByte;
  5. for (i = 0; i < sourceLen; i++)
  6. {
  7. highByte = source[i] >> 4;
  8. lowByte = source[i] & 0x0f ;
  9. highByte += 0x30;
  10. if (highByte > 0x39)
  11. dest[i * 2] = highByte + 0x07;
  12. else
  13. dest[i * 2] = highByte;
  14. lowByte += 0x30;
  15. if (lowByte > 0x39)
  16. dest[i * 2 + 1] = lowByte + 0x07;
  17. else
  18. dest[i * 2 + 1] = lowByte;
  19. }
  20. return ;
  21. }

//字节流转换为十六进制字符串的另一种实现方式

  1. void Hex2Str( const char *sSrc, char *sDest, int nSrcLen )
  2. {
  3. int i;
  4. char szTmp[3];
  5. for( i = 0; i < nSrcLen; i++ )
  6. {
  7. sprintf( szTmp, "%02X", (unsigned char) sSrc[i] );
  8. memcpy( &sDest[i * 2], szTmp, 2 );
  9. }
  10. return ;
  11. }

//十六进制字符串转换为字节流
//atoi,2个字符串字符变一个十六进制字节

  1. void HexStrToByte(const char* source, unsigned char* dest, int sourceLen)
  2. {
  3. short i;
  4. unsigned char highByte, lowByte;
  5. for (i = 0; i < sourceLen; i += 2)
  6. {
  7. highByte = toupper(source[i]);
  8. lowByte = toupper(source[i + 1]);
  9. if (highByte > 0x39)
  10. highByte -= 0x37;
  11. else
  12. highByte -= 0x30;
  13. if (lowByte > 0x39)
  14. lowByte -= 0x37;
  15. else
  16. lowByte -= 0x30;
  17. dest[i / 2] = (highByte << 4) | lowByte;
  18. }
  19. return ;
  20. }
  21. int main()
  22. {
  23. //char data[] = {0xFF,0x26,0xA0,0x0B,0xFF};
  24. char data[] = "FF26A00BFF12";
  25. char buffer[100];
  26. char i=0;
  27. memset(buffer, 0, sizeof(buffer));
  28. //ByteToHexStr(data, buffer, sizeof(data));
  29. //Hex2Str(data, buffer, sizeof(data));
  30. //printf("convert after:%d, %02x\n", strlen(buffer),buffer[i]);
  31. HexStrToByte(data,buffer,strlen(data));
  32. for(i=0;i<(strlen(data)/2);i++)
  33. {
  34. printf("convert after:%d, %02x\n", strlen(buffer),buffer[i]);
  35. }
  36. }

发表评论

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

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

相关阅读