【问题标题】:Have to load a hex file in c++ into a buffer?必须将 C++ 中的十六进制文件加载到缓冲区中吗?
【发布时间】:2020-11-02 05:05:25
【问题描述】:

我有一个包含 16 位十六进制数字的文件

4eff 0811 0101 0000 0002 etc

我想将它加载到缓冲区中,以便我可以提取信息并执行计算。这是我目前的代码

    std::ifstream myfile(filepath);

    if (myfile.is_open())
    {
        std::streampos size = myfile.tellg();

        std::vector<uint16_t> buffer;

        buffer.resize(size);

        for (int i = 0; i < size; i++) {

            myfile >> buffer[i];

            std::cout << buffer[i] << std::endl;
        }
    }
    else
    {
        std::cout << "Error: Could not load file" << std::endl;
    }

    myfile.close();

不幸的是,它不起作用。没有任何内容打印到屏幕上,这是我在运行代码后在终端上收到的警告。

warning C4244: 'argument': conversion from 'std::streamoff' to 'const unsigned int', possible loss of data

【问题讨论】:

  • 在哪里您会收到此警告?请edit您的问题在该行添加评论。
  • @Someprogrammerdude 编辑了它
  • 不应该输入&gt;&gt;hex&gt;&gt;buffer[i],因为您正在阅读十六进制?

标签: c++ file-io


【解决方案1】:

尝试使用std::hex

std::vector<uint16_t> getBufferFromHex(std::string const& fileName) {
  std::ifstream inf(fileName);
  assert(inf && "Error: Could not load file");
  inf >> hex;  // read in hex

  std::vector<uint16_t> buffer;
  buffer.reserve((std::filesystem::file_size(fileName) + 4) / 5); // C++17

  uint16_t input;
  while (inf >> input) { buffer.push_back(input); }
  
  return buffer;
}

【讨论】:

  • 我想过这个。我假设任何基于 nix 的文件都以换行符结尾。
猜你喜欢
  • 2014-11-21
  • 1970-01-01
  • 2015-05-09
  • 2019-03-27
  • 2021-02-03
  • 2016-04-30
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多