以十六进制输出一块内存的内容
在程序的调试过程中,经常需要输出各种数据,正常情况下使用 printf 和 cout 即可实现数据输出。然而在输出二进制数据时, printf 和 out 却有点无能为力。那么如何比较二进制数据是否正确呢?
方案一:文件输出。文件可以输入任何数据,但是需要在程序之外比较文件,这对于少量数据并不划算。
方案二:实现自定义的十六进制输出函数。当然,也可是八进制,一般而言十六进制更易看懂 ( 习惯 ) 。下面给出一个最近实现的此类函数。该函数可将指定长度任何内存数据以十六进制格式输出。 这个程序对 32 和 64位的 PC 均适用。
注意: %x 无法正确打印负数,负数总是打印成 32bit 整型数, 64 位 PC 也是如此。
- #include <stdio.h>
- #include <string>
- void HexOutput(const char* buf, size_t len)
- {
- printf("The Hex output of data :/n/t0x");
- for(size_t i=0; i<len; ++i)
- {
- unsigned char c = buf[i]; // must use unsigned char to print >128 value
- if( c< 16)
- {
- printf("0%x", c);
- }
- else
- {
- printf("%x", c);
- }
- }
- printf("/n");
- }
- int main()
- {
- char c = 'A';
- HexOutput(&c, 1);
- c = 'a';
- HexOutput(&c, 1);
- c = 255;
- printf("/t%x/n", c);
- HexOutput(&c, 1);
- c = -1;
- HexOutput(&c, 1);
- printf("/t%x/n", c);
- short sc = -8;
- HexOutput((char*)&sc, 2);
- printf("/t%x/n", sc);
- char buf[20] = {0};
- HexOutput(buf, 20);
- std::string str = "BRSACP";
- HexOutput(str.c_str(), str.size());
- buf[0] = 0xFD; buf[1] = 0xFE;
- HexOutput(buf, 2);
- memcpy(buf+2, str.c_str(), str.size());
- HexOutput(buf, 20);
- long long value = 0xFDFE425253414350LLU; // LLU or LL is necessary for 32 PC
- HexOutput((char*)&value, 8);
- Return 0;
- }
程序输出为:
The Hex output of data : //char c = 'A'
0x41
The Hex output of data : // char c=’a’
0x61
ffffffff
The Hex output of data : // char c =255
0xff
The Hex output of data : // char c = -1
0xff
ffffffff
The Hex output of data : // short sc = -8;
0xf8ff
fffffff8
The Hex output of data :
0x0000000000000000000000000000000000000000
The Hex output of data : // std::string str = "BRSACP";
0x425253414350
The Hex output of data : // buf[0] = 0xFD; buf[1] = 0xFE;
0xfdfe
The Hex output of data :
0xfdfe425253414350000000000000000000000000
The Hex output of data :
0x504341535242fefd
参见:
内存打印函数 C++ 谷歌