c++ - 在C++中将从文件读取的二进制数据转换为char指针

标签 c++ file hex binary-data char-pointer

我试图实现将从文件读取的二进制内容连续转换为字节。
我的文件samplefile.bin包含 16字节,它采用二进制格式。在Hexed.it中它将显示为。
enter image description here
在这种情况下,我需要提取十六进制格式的这些二进制值并将其存储到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传递给其他函数。但是此打印cout<<ptr[i]<<endl;的输出如下所示,这意味着未发生转换。
╠ ↕ ‼ ¶ ╙ O N ╥ í * : J Z [ \ J
我想要类似的内容
ptr[0] = 0xCC
ptr[1] = 0x12
...
ptr[15] = 0x4A
当我给出这样的cout<<(int)ptr[i]<<endl;时,我得到的0xCC的十进制值为204,而对于其他打印品也是如此。
我已经提到了C++ read binary file and convert to hexConvert binary file to hex notation。我没有找到确切的解决方案,因为他们在这两个链接中将其转换为字符串。我的意图不是这个。
我提到了这个类似于我的How properly to read data from binary file to char array。但这并不能解决我的问题。
我希望将此0xCC作为一个字节,并且应将其存储到ptr[0]中,并类似地存储其他值

How to workaround this issue ? Am I missing something here ? I am a newbie in C++ and please help me to resolve this issue


赞赏的努力。

最佳答案

读取文件并将其数据复制到char的 vector 。
您可以使用std::hex或std::uppercase之类的iomanip将整数值打印为十六进制。
不建议将原始指针分配并传递给另一个函数。只需传递一个char vector 或使用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;
}

关于c++ - 在C++中将从文件读取的二进制数据转换为char指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63248497/

相关文章:

c++ - 为什么在c++中实现基于类的优先级队列时需要重载operator<?

c++ - 如何将turbo c/c++程序连接到数据库

c++ - 外部模板 'inconsistent explicit instantiations'

python - 我如何编写/维护一个 .txt 文件,其名称和时间(分数列表)按时间增加排序?

java - Java中的byte[]到String : What does the output mean?

c++ - Qtsql 中的参数计数不匹配

windows - 如何使用需要特定文件名的 CLI 工具在批处理脚本中使用通配符?

c - 无休止的 while 循环和 fscanf 不将数据分配给结构

java - 用十六进制字符串加密和解密

c - 用C写十六进制(字节)