gpt4 book ai didi

c++ - 必须将c++中的十六进制文件加载到缓冲区中?

转载 作者:行者123 更新时间:2023-12-03 07:22:41 25 4
gpt4 key购买 nike

我有一个包含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

最佳答案

尝试使用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;
}

关于c++ - 必须将c++中的十六进制文件加载到缓冲区中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64640050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com