Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf raw data to a fixed length hex output

Tags:

c

format

printf

hex

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.

like image 998
rhlee Avatar asked Aug 16 '12 17:08

rhlee


1 Answers

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.

like image 115
sandyiscool Avatar answered Sep 22 '22 23:09

sandyiscool