[英]Printf raw data to a fixed length hex output
I have a struct, well pointer to a struct, and I wish to printf the first n bytes as a long hex number, or as a string of hex bytes. 我有一个结构,指向结构的指针,我希望将前n个字节打印为长十六进制数,或者作为十六进制字节的字符串。
Essentially I need the printf equivalent of gdb's examine memory command, x/nxb . 基本上我需要printf等效的gdb的检查内存命令,x / nxb。
If possible I would like to still use printf as the program's logger function just variant of it. 如果可能的话,我仍然希望使用printf作为程序的记录器功能只是它的变体。 Even better if I can do so without looping through the data. 如果我可以在不循环数据的情况下这样做,那就更好了。
Just took Eric Postpischil's advice and cooked up the following : 刚刚接受了Eric Postpischil的建议并制作了以下内容:
struct mystruc
{
int a;
char b;
float c;
};
int main(int argc, char** argv)
{
struct mystruc structVar={5,'a',3.9};
struct mystruc* strucPtr=&structVar;
unsigned char* charPtr=(unsigned char*)strucPtr;
int i;
printf("structure size : %zu bytes\n",sizeof(struct mystruc));
for(i=0;i<sizeof(struct mystruc);i++)
printf("%02x ",charPtr[i]);
return 0;
}
It will print the bytes as fas as the structure stretches. 它会在结构拉伸时将字节打印为fas。
Update : Thanks for the insight Eric :) I have updated the code. 更新:感谢洞察Eric :)我已经更新了代码。
Try this. 试试这个。 Say you have pointer to struct in pstruct
. 假设您在pstruct
有指向struct的指针。
unsigned long long *aslong = (unsigned long long *)pstruct;
printf("%08x%08x%08x%08x%08x%08x%08x%08x",
aslong[0],
aslong[1],
aslong[2],
aslong[3],
aslong[4],
aslong[5],
aslong[6],
aslong[7],
);
As Eric points out, this might print the bytes out-of-order. 正如Eric指出的那样,这可能会无序地打印字节。 So it's either this, or using unsigned char *
and (having a printf
with 64 arguments or using a loop). 所以它或者是这个,或者使用unsigned char *
和(具有64个参数的printf
或使用循环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.