C语言char*字符串数组和unsigned char[]数组的相互转换

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. void convertUnCharToStr(char* str, unsigned char* UnChar, int ucLen)
  5. {
  6. int i = 0;
  7. for(i = 0; i < ucLen; i++)
  8. {
  9. //格式化输str,每unsigned char 转换字符占两位置%x写输%X写输
  10. sprintf(str + i * 2, "%02x", UnChar[i]);
  11. }
  12. }
  13. void convertStrToUnChar(char* str, unsigned char* UnChar)
  14. {
  15. int i = strlen(str), j = 0, counter = 0;
  16. char c[2];
  17. unsigned int bytes[2];
  18. for (j = 0; j < i; j += 2)
  19. {
  20. if(0 == j % 2)
  21. {
  22. c[0] = str[j];
  23. c[1] = str[j + 1];
  24. sscanf(c, "%02x" , &bytes[0]);
  25. UnChar[counter] = bytes[0];
  26. counter++;
  27. }
  28. }
  29. return;
  30. }
  31. int main()
  32. {
  33. unsigned char src[6] = {0x12, 0x32,0x56,0x78,0x90,0xab};
  34. char buffer[20];//维数定义些
  35. convertUnCharToStr(buffer, src, 6);
  36. printf("%s\n", buffer);
  37. unsigned char dst[6];
  38. int len = strlen(buffer);
  39. cout << len << endl;
  40. convertStrToUnChar(buffer, dst);
  41. int i = 0;
  42. for(i = 0; i < 6; i++)
  43. {
  44. printf("%x ", dst[i]);
  45. }
  46. cout << endl;
  47. return 0;
  48. }