将原始数据打印到固定长度的十六进制输出

时间:2012-08-16 17:43:25

标签: c format hex printf

我有一个结构,指向结构的指针,我希望将前n个字节打印为长十六进制数,或者作为十六进制字节的字符串。

基本上我需要printf等效的gdb&s检查内存命令x / nxb。

如果可能的话,我仍然希望使用printf作为程序的记录器功能,只是它的变体。如果我能在不循环数据的情况下这样做,那就更好了。

2 个答案:

答案 0 :(得分:12)

刚刚接受了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;
}

它会在结构拉伸时将字节打印为fas。

更新:感谢洞察Eric :)我已经更新了代码。

答案 1 :(得分:1)

试试这个。假设您在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],
);

正如Eric指出的那样,这可能会无序地打印字节。所以它是这个,或使用unsigned char *和(printf有64个参数或使用循环)。