我正在尝试用C表示十六进制值的文件
像这样的声音:
char Msg[4] = {0x3f, 0x2a, 0x01, 0x52};
我正在文件中寻找的输出是这样的:“ 3f2a0152”
我正在使用fprintf在十六进制表示形式之前附加一些文本,但是我无法成功写入它
FILE *LOG_FILE= fopen("./Hex.log", "a");
fprinf(LOG_FILE, "%d OUT %x", Timestamp, Msg);
fclose(LOG_FILE);
任何建议?谢谢!
行:
fprintf(LOG_FILE, "%d OUT %x", Timestamp, Msg);
将Msg
衰减到一个指针(0x3f
的地址),然后打印出[[that。
fprintf(LOG_FILE, "%d OUT %02x%02x%02x%02x\n", Timestamp, Msg[0], Msg[1], Msg[2], Msg[3]);
此外,可能应该将它们指定为unsigned char
,以便在传递给fprintf
时不进行符号扩展。否则,您将不得不做一些丑陋的事情:
fprintf(LOG_FILE, "%d OUT %02x%02x%02x%02x\n", Timestamp, (unsigned)(Msg[0]), (unsigned)(Msg[1]), (unsigned)(Msg[2]), (unsigned)(Msg[3]));
如果您需要更通用的解决方案,则可以将一个函数组合在一起,例如:
void LogHex(FILE *fh, int tstamp, char *preamble, unsigned char *mem, size_t sz) { fprintf(fh, "%d %s", tstamp, preamble); for (size_t i = 0; i < sz; ++i) { fprintf(fh, "%02x", mem[i]); } fprintf(fh, "\n"); } : LogHex(LOG_FILE, Timestamp, "OUT ", Msg, sizeof(Msg));