将printf原始数据转换为固定长度的十六进制输出 [英] Printf raw data to a fixed length hex output

查看:1088
本文介绍了将printf原始数据转换为固定长度的十六进制输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体,指向结构体的指针,并且我希望将前n个字节作为长十六进制数字或者以十六进制字节形式显示。

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.

基本上我需要printf相当于gdb的检查内存命令x / nxb。

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

如果可能的话,我想仍然使用printf作为程序的记录器函数,它。更好的是,如果我可以这样做而不循环数据。

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.

推荐答案

刚刚拿走了Eric Postpischil的建议并制作了以下内容: / p>

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;
}

它会在结构展开时将字节打印为fas。

It will print the bytes as fas as the structure stretches.

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

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

这篇关于将printf原始数据转换为固定长度的十六进制输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆