简体   繁体   中英

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.

Essentially I need the printf equivalent of gdb's examine memory command, x/nxb .

If possible I would like to still use printf as the program's logger function just variant of it. Even better if I can do so without looping through the data.

Just took Eric Postpischil's advice and cooked up the following :

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.

Update : Thanks for the insight Eric :) I have updated the code.

Try this. Say you have pointer to struct in pstruct .

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. So it's either this, or using unsigned char * and (having a printf with 64 arguments or using a loop).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM