将数组的十六进制值转换为另一个数组的字符串值

标签 c string char hex byte

我正在尝试将一个数组的十六进制值转换为另一个数组的字符。这是唯一的方法,我能找到但不起作用。

感谢您的帮助!

char tmp[] = {0x81, 0x00, 0x00, 0x00, 0x12, 0x05};
char new[12];

for (int i = 0; i < 6; i++) {
    printf(" %x", tmp[i]);
    sprintf(new + i, "%x", tmp[i]);
}
for (int i = 0; i < 12; i++) {
        printf(" %c", new[i]);
}
printf("new: %s\n", new);

这是输出:

 81 0 0 0 12 5
 8 0 0 0 1 5
new: 800015

所以,它缺少一些字节......

最佳答案

可能

char tmp[] = {0x81, 0x00, 0x00, 0x00, 0x12, 0x05};
char new[6];

必须是

int tmp[] = {0x81, 0x00, 0x00, 0x00, 0x12, 0x05};
char new[6*2+1];

sprintf(tmp + i, "%x", tmp[i]);

必须是

sprintf(new + 2*i, "%02x", tmp[i]);

for (int i = 0; i < 6; i++) {
        printf(" %c", new[i]);
}

必须是

for (int i = 0; i < 6*2; i++) {
        printf(" %c", new[i]);
}

执行:

/tmp % ./a.out
 81 0 0 0 12 5 8 1 0 0 0 0 0 0 1 2 0 5new: 810000001205

valgrind 下:

/tmp % valgrind ./a.out
==15557== Memcheck, a memory error detector
==15557== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==15557== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==15557== Command: ./a.out
==15557== 
 81 0 0 0 12 5 8 1 0 0 0 0 0 0 1 2 0 5new: 810000001205
==15557== 
==15557== HEAP SUMMARY:
==15557==     in use at exit: 0 bytes in 0 blocks
==15557==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==15557== 
==15557== All heap blocks were freed -- no leaks are possible
==15557== 
==15557== For counts of detected and suppressed errors, rerun with: -v
==15557== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)

关于将数组的十六进制值转换为另一个数组的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54575278/

相关文章:

Java - 如何匹配包含单引号的正则表达式模式?

c - char 数组声明形式之间的区别

c++ - 拆分并从字符串转换为字符数组

c - 如何在 c 中使用 strcat 连接 char 指针?

c - 为什么 C 使用星号来声明指针,而不是像 Pascal 那样使用插入符号?

c - 定义 ANSI C ISO/IEC-9899 中缺少的 bool 类型 :1990 in Visual Studio 2012 RC

java - 为什么 String equals() 返回 false(涉及自定义比较器)?

c - 关于 char 数组和指向它们的指针,我错过了哪些语法

string - 用 bash 替换字符串中的百分比转义字符(%20、%5B、…)

c++ - char* 数组的问题