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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/920511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:57:42  来源:igfitidea点击:

How to visualize bytes with C/C++

c++c

提问by OhioDude

I'm working my way through some C++ training. So far so good, but I need some help reinforcing some of the concepts I am learning. My question is how do I go about visualizing the byte patterns for objects I create. For example, how would I print out the byte pattern for structs, longs, ints etc?

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

I understand it in my head and can understand the diagrams in my study materials, I'd just like to be able to programaticially display byte patterns from within some of my study programs.

我在头脑中理解它并且可以理解我的学习材料中的图表,我只是希望能够从我的一些学习程序中以编程方式显示字节模式。

I realize this is pretty trivial but any answers would greatly help me hammer in these concepts.

我意识到这是非常微不足道的,但任何答案都会极大地帮助我敲定这些概念。

Thanks.

谢谢。

Edit: I use mostly XCode for my other development projects, but have VMs for Windows7 and fedora core. At work I use XP with visual studio 2005. ( I can't comment as I am still a n00b here :D)

编辑:我的其他开发项目主要使用 XCode,但有适用于 Windows7 和 Fedora 核心的虚拟机。在工作中,我在 Visual Studio 2005 中使用 XP。(我无法发表评论,因为我在这里仍然是 n00b :D)

I used unwind's solution which is about what I am looking for. I am also thinking that maybe I could just use the dos DEBUG command as I'd also like to look at chunks for memory too. Again, this is just to help me reinforce what I am learning. Thanks again people!

我使用了 unwind 的解决方案,这与我正在寻找的有关。我也在想,也许我可以只使用 dos DEBUG 命令,因为我也想查看内存块。同样,这只是为了帮助我巩固我正在学习的内容。再次感谢人们!

回答by unwind

You can use a function such as this, to print the bytes:

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

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

Usage would look like this, for instance:

用法如下所示,例如:

int x = 37;
float y = 3.14;

print_bytes(&x, sizeof x);
print_bytes(&y, sizeof y);

This shows the bytes just as raw numerical values, in hexadecimal which is commonly used for "memory dumps" like these.

这将字节显示为原始数值,以十六进制表示,通常用于像这样的“内存转储”。

On a random (might even be virtual, for all I know) Linux machine running a "Intel(R) Xeon(R)" CPU, this prints:

在运行“Intel(R) Xeon(R)”CPU 的随机(甚至可能是虚拟的)Linux 机器上,打印:

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

This handily also demonstrates that the Intel family of CPU:s really are little endian.

这也很方便地表明 Intel 系列 CPU:s 确实是little endian

回答by OhioDude

If you are using gcc and X, you can use the DDD debuggerto draw pretty pictures of your data structures for you.

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

回答by juanchopanza

Just for completeness, a C++ example:

只是为了完整性,一个 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);
}

回答by Dolphin

Most (visual) debuggers have a "View Memory' option. IIRC the one in Xcode is pretty basic, just showing bytes in HEX and ASCII, with a variable line length. Visual Studio (Debug->Windows->Memory in Vs2008) can format the hex portion as different integer lengths, or floating point, change the endianess, and display ANSI or UNICODE text. You can also set just about any number for the width of the window (I think xcode only lets you go to 64 bytes wide) The other IDE I have here at work has a lot of options, though not quite as many as VS.

大多数(视觉)调试器都有“查看内存”选项。Xcode 中的 IIRC 非常基本,只显示十六进制和 ASCII 字节,行长可变。Visual Studio(Vs2008 中的调试->Windows->内存)可以将十六进制部分格式化为不同的整数长度或浮点数,更改字节序,并显示 ANSI 或 UNICODE 文本。您还可以为窗口的宽度设置任何数字(我认为 xcode 只允许您使用 64 字节宽) 我在这里工作的另一个 IDE 有很多选择,虽然没有 VS 那么多。

回答by Scott Jasin

A little bit by bit console program i whipped up, hope it helps somebody

我一点一点的控制台程序,希望它可以帮助某人

#include <iostream>
#include <inttypes.h>
#include <vector>
using namespace std;
typedef  vector<uint8_t> ByteVector;
///////////////////////////////////////////////////////////////
uint8_t Flags[8] = { 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
void print_bytes(ByteVector Bv){
    for (unsigned i = 0; i < Bv.size(); i++){
        printf("Byte %d [ ",i);
        for (int j  = 0;j < 8;++j){
            Bv[i] & Flags[j] ? printf("1") : printf("0");
        }
        printf("]\n");
    }
}
int main(){
    ByteVector Bv;
    for (int i = 0; i < 4; ++i) { Bv.push_back(i); }
    print_bytes(Bv);
}

回答by TimW

Or if you have the boost lib and want to use lambda evaluations you can do it this way ...

或者,如果您有 boost lib 并想使用 lambda 评估,您可以这样做...

template<class T>
void bytePattern( const T& object )
{
    typedef unsigned char byte_type;
    typedef const byte_type* iterator;

    std::cout << "Object type:" << typeid( T ).name() << std::hex;
    std::for_each( 
        reinterpret_cast<iterator>(&object), 
        reinterpret_cast<iterator>(&object) + sizeof(T), 
        std::cout << constant(' ') << ll_static_cast<int>(_1 )&&0xFF );   
    std::cout << "\n";
}

回答by jrharshath

try this:

尝试这个:

MyClass* myObj = new MyClass();
int size=sizeof(*myObj);
int i;
char* ptr = obj; // closest approximation to byte
for( i=0; i<size; i++ )
    std::cout << *ptr << endl;

Cheers,

干杯,

jrh.

jrh。