1. 程式人生 > >C語言char*字符串數組和unsigned char[]數組的相互轉換

C語言char*字符串數組和unsigned char[]數組的相互轉換

sso pri sprint %x chart += ++ nbsp class

  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. }

C語言char*字符串數組和unsigned char[]數組的相互轉換