如果我有以下C数组:
char arr[4];
arr[0] = 0x11;
arr[1] = 0xc0;
arr[2] = 0x0c;
arr[3] = 0x00;
如何将上述数据转换为字符串,如下所示?
char* str = "11c00c00";
答案 0 :(得分:2)
int main()
{
char arr[4];
arr[0] = 0x11;
arr[1] = 0xc0;
arr[2] = 0x0c;
arr[3] = 0x00;
size_t len = sizeof(arr) / sizeof(*arr);
char* str = (char*)malloc(len * 2 + 1);
for (size_t i = 0; i < len; i++)
{
const static char table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c','d','e','f' };
unsigned char c = (unsigned char)(arr[i]);
unsigned int lowbyte = c & 0x0f;
unsigned int highbyte = (c >> 4) & 0x0f;
str[2 * i] = table[highbyte];
str[2 * i + 1] = table[lowbyte];
}
str[2 * len] = '\0';
printf("%s\n",str);
return 0;
}
答案 1 :(得分:0)
将每个字符转换为无符号字符(因此0xc0不是负数),然后将其转换为整数并输出为两位十六进制值。
#include <stdlib.h>
#include <stdio.h>
#define INT(x) ((int)(unsigned char)(x))
int main()
{
char arr[4];
arr[0] = 0x11;
arr[1] = 0xc0;
arr[2] = 0x0c;
arr[3] = 0x00;
char *str;
str=malloc(32);
sprintf(str, "%02x%02x%02x%02x",
INT(arr[0]), INT(arr[1]), INT(arr[2]), INT(arr[3]));
puts(str);
}
输出是:
11c00c00