我从 BMP 标头获取 ASCII 符号而不是数字

-1 c++ bmp

我正在尝试从 .bmp 文件中获取 BITMAPFILEHEADER 部分。我期望看到一些数字,但有 ASCII 符号。如何解决这个问题呢?

std::string path;
std::ifstream file;

path = "C:\\Users\\user\\Desktop\\Emp.bmp";

file.open(path);

if (!file.is_open())
{
    std::cout << "ERROR";
}
else
{
    char fromfile[14];

    file.read(fromfile, 14);

    std::cout << fromfile;
    file.close();
}
Run Code Online (Sandbox Code Playgroud)

我尝试将 ASCII 输出转换为十六进制符号,并且我有正确的数据(它与十六进制编辑器数据匹配),但我不明白为什么我从程序输出中获取 ASCII

woh*_*tad 7

这行:

std::cout << fromfile;
Run Code Online (Sandbox Code Playgroud)

fromfile其视为以 null 结尾的字符串,因为它是 s 数组char

如果你想查看字节的数值,可以使用:

for (auto const & c : fromfile)
{
    std::cout << static_cast<int>(c) << ", ";
}
Run Code Online (Sandbox Code Playgroud)

如果您只想查看正值(因为char可以带符号),则循环体应该是:

std::cout << static_cast<int>(static_cast<unsigned char>(c)) << ", ";
Run Code Online (Sandbox Code Playgroud)

如果您想要十六进制值,请将其替换为:

std::cout << std::hex << static_cast<int>(static_cast<unsigned char>(c)) << ", ";
Run Code Online (Sandbox Code Playgroud)

另一个问题是您以文本模式(默认)打开文件,而不是以更适合您目的的二进制模式打开它:

//--------------vvvvvvvvvvvvvvvv-
file.open(path, std::ios::binary);
Run Code Online (Sandbox Code Playgroud)