如何使用C/C++可视化字节

Ohi*_*ude 10 c c++

我正在通过一些C++培训.到目前为止一切顺利,但我需要一些帮助来加强我正在学习的一些概念.我的问题是如何可视化我创建的对象的字节模式.例如,我如何打印结构,长整数,整数等字节模式?

我理解它可以理解我的学习材料中的图表,我只是想能够在我的一些学习计划中以编程方式显示字节模式.

我意识到这是非常微不足道的,但任何答案都将极大地帮助我理解这些概念.

谢谢.

编辑:我主要使用XCode进行其他开发项目,但是有适用于Windows7和fedora核心的VM.在工作中我使用XP与visual studio 2005.(我无法评论,因为我仍然是一个n00b:D)

我使用了unwind的解决方案,这是我正在寻找的.我也在想,也许我可以使用dos DEBUG命令,因为我也想查看块的内存.再次,这只是为了帮助我强化我正在学习的东西.再次感谢大家!

unw*_*ind 25

你可以使用这样的函数来打印字节:

void print_bytes(const void *object, size_t size)
{
  // This is for C++; in C just drop the static_cast<>() and assign.
  const unsigned char * const bytes = static_cast<const unsigned char *>(object);
  size_t i;

  printf("[ ");
  for(i = 0; i < size; i++)
  {
    printf("%02x ", bytes[i]);
  }
  printf("]\n");
}
Run Code Online (Sandbox Code Playgroud)

用法看起来像这样,例如:

int x = 37;
float y = 3.14;

print_bytes(&x, sizeof x);
print_bytes(&y, sizeof y);
Run Code Online (Sandbox Code Playgroud)

这显示的字节就像原始数值一样,以十六进制表示,通常用于这些"内存转储".

对于运行"Intel(R)Xeon(R)"CPU的随机(甚至可能是虚拟的,据我所知)Linux机器,它打印:

[ 25 00 00 00 ]
[ c3 f5 48 40 ]

这也轻而易举地说明了Intel系列的CPU:s真的是小端.


小智 5

如果您使用的是gcc和X,则可以使用DDD调试器为您绘制数据结构的漂亮图片.


jua*_*nza 5

只是为了完整性,一个 C++ 示例:

#include <iostream>

template <typename T>
void print_bytes(const T& input, std::ostream& os = std::cout)
{
  const unsigned char* p = reinterpret_cast<const unsigned char*>(&input);
  os << std::hex << std::showbase;
  os << "[";
  for (unsigned int i=0; i<sizeof(T); ++i)
    os << static_cast<int>(*(p++)) << " ";
  os << "]" << std::endl;;
}

int main()
{
  int i = 12345678;
  print_bytes(i);
  float x = 3.14f;
  print_bytes(x);
}
Run Code Online (Sandbox Code Playgroud)