linux c 字符串转化十六进制
作者:互联网
参考链接:
https://blog.csdn.net/sweetfather/article/details/103593040
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define MAX_DATA_SIZE 1024 static int convert_string2hex(unsigned char *in_data, int in_data_len, unsigned char *out_data, int *out_data_len) { int i; int loop_count; int convert_point = 0; int mem_point = 0; unsigned char convert_result; unsigned char temp[3] = {0}; /* 为啥是3呢? */ /* 检查参数有效性 */ if (in_data == NULL || in_data_len <= 0 || out_data == NULL || out_data_len == NULL || (in_data_len % 2) != 0) { printf("invalid parameters\n"); return -1; } /* 判断是否超过16进制范围 0 ~ F */ for (i = 0; i < in_data_len; i++) { if ((in_data[i] < '0') || (in_data[i] > 'f') || ((in_data[i] > '9') &&(in_data[i] < 'A'))) { printf("out of range\n"); return -1; } } loop_count = in_data_len / 2; memset(out_data, 0x00, *out_data_len); *out_data_len = 0; for (i = 0; i < loop_count; i++) { memset(temp, 0x00, sizeof(temp)); memcpy(temp, in_data + convert_point, 2); convert_point += 2; convert_result = strtoul(temp, NULL, 16); memcpy(out_data + mem_point, &convert_result, sizeof(unsigned char)); mem_point += sizeof(unsigned char); *out_data_len += sizeof(unsigned char); } return 0; } int main(int argc, char const *argv[]) { // unsigned char in_data[MAX_DATA_SIZE] = {0}; char SysUniqueID[25] = {0}; unsigned char in_data[MAX_DATA_SIZE] = {"c06900f0c1003cde002c1f00579300ab7500857f00409300"}; int in_data_len = MAX_DATA_SIZE; unsigned char out_data[MAX_DATA_SIZE] = {0}; int out_data_len = MAX_DATA_SIZE; int i; // scanf("%s", in_data); in_data_len = strlen(in_data); convert_string2hex(in_data, in_data_len, out_data, &out_data_len); for (i = 0; i < out_data_len; i++) { printf("0x%02x ", out_data[i]); } printf("\n"); sprintf(SysUniqueID,"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",out_data[0], out_data[1],out_data[2],out_data[3],out_data[4],out_data[5],out_data[6],out_data[7],out_data[8],out_data[9],out_data[10], out_data[11],out_data[12],out_data[13],out_data[14],out_data[15],out_data[16],out_data[17],out_data[18],out_data[19],out_data[20], out_data[21],out_data[22],out_data[23]); printf("%s\n", SysUniqueID); return 0; }
标签:十六进制,int,len,char,linux,字符串,02x%,data,out 来源: https://www.cnblogs.com/hzijone/p/14768689.html