zoukankan      html  css  js  c++  java
  • 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 ", 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;  
  • 相关阅读:
    webpack 关于跨域的配置
    如何使用css变量
    样式重置
    vue+element_ui上传文件,并传递额外参数(自动上传)
    LeetCode-46-全排列
    LeetCode-39-组合总数
    LeetCode-33-搜索旋转排序数组
    LeetCode-207-课程表
    LeetCode-15-三数之和
    LeetCode-盛最多水的容器
  • 原文地址:https://www.cnblogs.com/dpf-learn/p/7580568.html
Copyright © 2011-2022 走看看