char数组与十六进制字符串互转

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define hexStrToUint8(dest, str, strLen) {\
      unsigned int val;\
      for(int i = 0; i < strLen; i += 2){\
        sscanf(str + i, "%02x", &val);\
        dest[i / 2] = val;\
      }\
    }

#define logBuf(buf, len)\
    for(int i = 0; i < len; i++){\
      printf("0x%02x ", (unsigned char)buf[i]);\
    }\
    printf("\n");

#define uint8ToHexStr(dest, src, len)\
    for(int i = 0; i < len; i++ ){\
      sprintf(&dest[i * 2], "%02x", (unsigned char)src[i]);\
    }\
    dest[len * 2] = '\0';

int main(){
    char f[] = "32FF14981533F9F8F7E7E8E9EE";
    char dst[100];    
    char dst_2[100];    

    hexStrToUint8(dst, f, sizeof(f));
    logBuf(dst, sizeof(f) / 2);
    
    uint8ToHexStr(dst_2, dst, sizeof(f) / 2);    
    printf("%s\n", dst_2);
    return 0;
}
posted @ 2022-07-19 10:29  feipeng8848  阅读(1076)  评论(0编辑  收藏  举报