我正在尝试将字符缓冲区的前8个字节分配为“ 00 00 00 00 00 00 00 A0”。我能够验证缓冲区的构造正确。每当我尝试使用实用程序进行十六进制转储时,都会得到意外的输出。不知道,如果我在这里想念其他东西。
#include<stdio.h>
#include<string.h>
static void hexdump(const char *src, int count)
{
int i;
if (count == 0)
return;
for (i = 0; i < count; ++i) {
printf("%02x ", src[i]);
if ((i + 1) % 16 == 0)
printf("\n");
}
printf("\n");
}
int main() {
char msg_buff[148];
memset(msg_buff, 0, 148);
int a[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0};
sprintf(msg_buff, "%02x %02X %02X %02X %02X %02X %02X %02X", a[0], a[1],
a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
printf("packet %s \n", msg_buff); // 00 00 00 00 00 00 00 A0
hexdump(msg_buff, 148);
}
我的输出
packet 00 00 00 00 00 00 00 A0
30 30 20 30 30 20 30 30 20 30 30 20 30 30 20 30
30 20 30 30 20 41 30 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00
预期产量
packet 00 00 00 00 00 00 00 A0
00 00 00 00 00 00 00 A0 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00
最佳答案
首先,您需要从代码中的以下函数中删除a[8]
,因为a[]
的长度为8,但是您的代码有9个成员:sprintf(msg_buff, "%02X %02X %02X %02X %02X %02X %02X %02X", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
其次,您需要更改定义的变量类型,代码应如下所示:
#include<stdio.h>
#include<string.h>
static void hexdump(const char *src, int count)
{
int i;
if (count == 0)
return;
for (i = 0; i < count; ++i) {
printf("%02x ", src[i]);
if ((i + 1) % 16 == 0)
printf("\n");
}
printf("\n");
}
int main() {
unsigned char msg_buff[148];
memset(msg_buff, 0, 148);
unsigned char a[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0 };
sprintf(msg_buff, "%02X %02X %02X %02X %02X %02X %02X %02X", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
printf("packet %s \n", msg_buff); // 00 00 00 00 00 00 00 A0
hexdump(msg_buff, 148);
return 0;
}
关于c - 十六进制到字符转换和转储输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45824186/