解析二进制文件时,我如何将整数变量显示为' cout '中的预期ASCII字母?



当我在命令行中使用hexdump -C来检查这个MIDI文件时,我们可以看到这个二进制文件的一些字节是ASCII字母,这意味着是人类可读的文本。

00000000  4d 54 68 64 00 00 00 06  00 01 00 08 00 78 4d 54  |MThd.........xMT|
000024f0  2f 00 4d 54 72 6b 00 00  00 19 00 ff 21 01 00 00  |/.MTrk......!...|
00002500  ff 03 0c 62 79 20 42 65  65 74 68 6f 76 65 6e 00  |...by Beethoven.|
00002510  ff 2f 00 4d 54 72 6b 00  00 00 18 00 ff 21 01 00  |./.MTrk......!..|

出于调试的目的,当我有一个变量,它包含一个整数,我知道它代表一个ASCII字符字符串,我想简单地在cout中显示ASCII字符。

在本例中,文件的前四个字节是0x4d546864,代表字母MThd

uint32_t n32Bits = 0;
ifs.read((char*)&n32Bits, sizeof(uint32_t));
n32Bits = BigEndianToLittleEndian(n32Bits); // reverse byte order

这是一个整数:

std::cout << "n32Bits: " << n32Bits <<std::endl; // 1297377380

我可以很容易地显示为hex:

std::cout << "n32Bits: " << std::hex << n32Bits <<std::endl; // 4d546864

现在,我希望这一行输出字母MThd,就像hexdump一样。

std::cout << "n32Bits: " << std::ascii << n32Bits <<std::endl; // compile error.

是否有一些简单的内置方法来转储ASCII字母从整数表示ASCII字母?

没有像std::ascii这样的格式规范,但有一个string构造函数可以使用:

std::string int2str((char*)&n32Bits, 4);
std::cout << "n32Bits: " << int2str << std::endl;

这个构造函数接受一个char缓冲区和长度。

没有像十六进制转储那样将原始字节作为ASCII字符串打印的内置函数。您必须自己手动完成,例如:

#include <algorithm>
#include <iterator>
#include <cctype>
#include <cstring>
char buffer[sizeof(n32Bits)];
std::memcpy(buffer, &n32Bits, sizeof(n32Bits));
std::transform(std::begin(buffer), std::end(buffer), std::begin(buffer),
[](unsigned char ch){ return std::isprint(ch) ? static_cast<char>(ch) : '.'; }
);
std::cout << "n32Bits: ";
std::cout.write(buffer, sizeof(buffer));
std::cout << std::endl;

在线演示
int a = 0x4d546864;
// swap_bytes(a);
int b[] =   {a, 0};
cout << (char*)b <<endl;