问题描述
我正在通过一些C ++培训来努力.到目前为止还不错,但是我需要一些帮助加强我正在学习的一些概念.我的问题是如何为创建对象的字节模式可视化.例如,我如何打印为结构,longs,ints等的字节模式?
我在脑海中理解它,并且可以理解我的研究材料中的图表,我希望能够从我的某些学习计划中进行程序上显示字节模式.
我意识到这很微不足道,但是任何答案都会极大地帮助我锤击这些概念.
谢谢.
编辑:我主要用于其他开发项目,但Windows7和Fedora Core具有VM.在工作中,我将XP与Visual Studio 2005一起使用. (我无法评论,因为我仍然是N00B:D)
我使用了Undind的解决方案,这是关于我想要的.我还认为也许我可以使用DOS调试命令,因为我也想查看记忆的块.同样,这只是为了帮助我加强自己的学习.再次感谢人们!
推荐答案
您可以使用这样的函数来打印字节:
static void print_bytes(const void *object, size_t size) { #ifdef __cplusplus const unsigned char * const bytes = static_cast<const unsigned char *>(object); #else // __cplusplus const unsigned char * const bytes = object; #endif // __cplusplus size_t i; printf("[ "); for(i = 0; i < size; i++) { printf("%02x ", bytes[i]); } printf("]\n"); }
用法看起来像这样,例如:
int x = 37; float y = 3.14; print_bytes(&x, sizeof x); print_bytes(&y, sizeof y);
这将字节显示为原始数值值,在十六进制中,通常用于这样的"内存转储".
随机(我所知道的所有可能是虚拟的)Linux机器运行" Intel(r)Xeon(r)" CPU,此打印:
[ 25 00 00 00 ] [ c3 f5 48 40 ]
这也简单地证明了CPU的英特尔家族:S确实是 Little Endian .
其他推荐答案
如果您使用的是GCC和X,则可以使用 ddd ddd ddd debugger 为您绘制数据结构的漂亮图片.
其他推荐答案
仅出于完整性,一个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); }