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

  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. void convertUnCharToStr(char* str, unsigned char* UnChar, int ucLen)  
  6. {  
  7.     int i = 0;  
  8.     for(i = 0; i < ucLen; i++)  
  9.     {  
  10.         //格式化输str,每unsigned char 转换字符占两位置%x写输%X写输  
  11.         sprintf(str + i * 2, "%02x", UnChar[i]);  
  12.     }  
  13. }  
  14.   
  15. void convertStrToUnChar(char* str, unsigned char* UnChar)  
  16. {  
  17.     int i = strlen(str), j = 0, counter = 0;  
  18.     char c[2];  
  19.     unsigned int bytes[2];  
  20.   
  21.     for (j = 0; j < i; j += 2)   
  22.     {  
  23.         if(0 == j % 2)  
  24.         {  
  25.             c[0] = str[j];  
  26.             c[1] = str[j + 1];  
  27.             sscanf(c, "%02x" , &bytes[0]);  
  28.             UnChar[counter] = bytes[0];  
  29.             counter++;  
  30.         }  
  31.     }  
  32.     return;  
  33. }  
  34.   
  35. int main()  
  36. {  
  37.     unsigned char src[6] = {0x12, 0x32,0x56,0x78,0x90,0xab};  
  38.     char buffer[20];//维数定义些  
  39.     convertUnCharToStr(buffer, src, 6);    
  40.     printf("%s\n", buffer);  
  41.   
  42.   
  43.     unsigned char dst[6];  
  44.     int len = strlen(buffer);  
  45.     cout << len << endl;  
  46.     convertStrToUnChar(buffer, dst);  
  47.       
  48.     int i = 0;  
  49.     for(i = 0; i < 6; i++)  
  50.     {  
  51.         printf("%x ", dst[i]);  
  52.     }  
  53.     cout << endl;  
  54.   
  55.   
  56.     return 0;  
posted @   丁培飞  阅读(15745)  评论(2)    收藏  举报
编辑推荐:
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
阅读排行:
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 管理100个小程序-很难吗
· 在SqlSugar的开发框架中增加对低代码EAV模型(实体-属性-值)的WebAPI实现支持
· 如何统计不同电话号码的个数?—位图法
· 使用这个工具,基于代码仓库直接生成教程文档,感觉比我自己写的还好
点击右上角即可分享
微信分享提示