我正在努力实现将从文件读取的二进制内容连续转换为字节。 我的文件samplefile.bin
包含16个字节,并且是二进制形式的。 它会像这样显示。
在这种情况下,我需要以十六进制格式提取这些二进制值,并将其存储到char*
中
我会把我的示例代码贴在这里。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
uint8_t *ptr;
long size;
ifstream file ("samplefile.bin", ios::in|ios::binary|ios::ate);
size = file.tellg();
std::vector<uint8_t> memblock(size);
file.seekg (0, ios::beg);
file.read(reinterpret_cast<char*>(&memblock[0]), size);
file.close();
ptr = new uint8_t[size];
int z=0;
for(int i=0; i < memblock.size(); i++)
{
std::cout << memblock.at(i) << ' ';
z=memblock.at(i)&0xff;
ptr[i] = z;
}
cout<<"Output"<<endl;
for (int i=0;i<memblock.size();i++)
{
cout<<ptr[i];
}
delete []ptr;
return 0;
}
我希望将ptr
传递给其他函数。 但是这个printcout<
╠ ↕ ‼ ¶ ╙ O N ╥ í * : J Z [ \ J
我想要下面这样的东西
ptr[0] = 0xCC
ptr[1] = 0x12
...
ptr[15] = 0x4A
当我像这样给出cout<<<(int)ptr[I]<
0xcc
的十进制值,作为204
,对于其他打印也是如此。
我已经提到了C++读取二进制文件并转换为十六进制,以及将二进制文件转换为十六进制表示法。 我没有找到确切的解决方案,因为在这两个链接中,他们正在把它转换成字符串。 我的意图不是这个。
我提到了如何正确地从二进制文件读取数据到char数组,它看起来与我的相似。 但它没有解决我的问题。
我希望将此0xcc
作为单个字节存储,并且应将其存储到PTR[0]
中,对于其他值也应如此
如何解决这个问题? 我是不是漏掉了什么? 我是一个C++新手,请帮助我解决这个问题
对这些努力表示赞赏。
读取文件并将其数据复制到Char的矢量中。 您可以像使用std::hex或std::uppercase一样使用iomanip将整数值打印为hex。
不建议将原始指针分配并传递到另一个函数。 只需传递一个char向量或使用unique_ptr,就可以避免内存问题。
#include <iostream>
#include <iomanip>
std::ifstream file("samplefile.bin", ios::binary);
auto mem = std::vector<char>(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
for (char c : mem)
{
std::cout << std::uppercase << std::hex << static_cast<int>(c) << endl;
}
您的代码中存在多个问题,最根本的问题是,当将std::byte8_t
提供给输出流时,您似乎期望在默认情况下将其表示为一个hexdump。 事实并非如此。 您需要显式地告诉流为您执行必要的格式化。 如果您想要存储该表示,那么您还需要存储流化结果。
条条大路通罗马,不幸的是C++标准IO流库并没有使处理字节流非常符合人体工程学。 但这里有一种方法:
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
using byte = std::uint8_t;
auto read_bytes(std::istream& is, std::vector<byte>& bytes) -> std::istream& {
return is.read(& reinterpret_cast<char&>(bytes[0]), bytes.size());
}
auto hexdump(std::vector<byte> const& bytes) -> std::string {
auto ostr = std::ostringstream();
ostr << std::uppercase << std::hex << std::setw(2) << std::setfill('0');
for (auto const c : bytes) {
ostr << int{c};
}
return ostr.str();
}
int main(int argc, char** argv) {
if (argc != 2) {
errno = EINVAL;
std::perror(argv[0]);
return 1;
}
auto fs = std::ifstream(argv[1], std::ios_base::binary | std::ios_base::ate);
auto const size = fs.tellg();
fs.seekg(0);
auto buffer = std::vector<byte>(size);
if (not read_bytes(fs, buffer)) {
std::perror("Failed to read file");
return 1;
}
std::cout << hexdump(buffer) << "\n";
}