【发布时间】:2018-07-16 00:04:56
【问题描述】:
我正在尝试创建一个以十六进制形式显示 bmp 文件输出的程序。到目前为止,我得到了输出,但我需要以某种方式组织它。
需要组织的方式是将 bmp 文件的地址放在左列,然后按照它们在文件中出现的顺序在每行中以十六进制显示 16 个字节的数据。同时在每 8 个字节之间留出一个额外的空间。到目前为止,我已经显示了十六进制,我只需要帮助来组织它。
我有什么:
我想让它看起来像什么:
这是我的代码:
#include <iostream> // cout
#include <fstream> // ifstream
#include <iomanip> // setfill, setw
#include <stdlib.h>
using namespace std; // Use this to avoid repeated "std::cout", etc.
int main(int argc, char *argv[]) // argv[1] is the first command-line argument
[enter image description here][1]{
// Open the provided file for reading of binary data
ifstream is("C:\\Users\\Test\\Documents\\SmallTest.bmp", ifstream::binary);
if (is) // if file was opened correctly . . .
{
is.seekg(0, is.end); // Move to the end of the file
int length = is.tellg(); // Find the current position, which is file length
is.seekg(0, is.beg); // Move to the beginning of the file
char * buffer = new char[length]; // Explicit allocation of memory.
cout << "Reading " << length << " characters... ";
is.read(buffer, length); // read data as a block or group (not individually)
if (is)
cout << "all characters read successfully.\n";
else
cout << "error: only " << is.gcount() << " could be read.\n";
is.close();
// Now buffer contains the entire file. The buffer can be printed as if it
// is a _string_, but by definition that kind of print will stop at the first
// occurrence of a zero character, which is the string-ending mark.
cout << "buffer is:\n" << buffer << "\n"; // Print buffer
for (int i = 0; i < 100; i++) // upper range limit is typically length
{
cout << setfill('0') << setw(4) << hex << i << " ";
cout << setfill('0') << setw(2) << hex << (0xff & (int)buffer[i]) << " ";
}
delete[] buffer; // Explicit freeing or de-allocation of memory.
}
else // There was some error opening file. Show message.
{
cout << "\n\n\tUnable to open file " << argv[1] << "\n";
}
return 0;
}
【问题讨论】:
-
你必须更好地解释你在寻找什么作为输出。左栏的标题是什么意思?
-
对不起,不是标题,我的意思是 bmp 地址在左列。我附上了我当前输出的图像以及我的输出需要的样子。
-
您可能会考虑 C++ 函数 std::string dumpByteHex(...) 答案:stackoverflow.com/a/46083427/2785528
-
我删除了标签
bmp,因为您的代码并不是真正的关于 BMP 文件。这可以询问任何文件类型(甚至任何十六进制转储)。