JerSci
JerSci

Reputation: 197

Have to load a hex file in c++ into a buffer?

I have a file that contains 16 bit hex digits like so

4eff 0811 0101 0000 0002 etc

And i want to load this into a buffer so that i can extract info and perform calculations. This is my code so far

    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();

unfortunately it isn't working. Nothing prints to screen and this is the warning i get on the terminal after i've run the code.

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

Upvotes: 1

Views: 150

Answers (1)

Kostas
Kostas

Reputation: 4176

Try using 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;
}

Upvotes: 1

Related Questions