Search code examples
c++vectorbinaryhexbitset

Reading individual hex values line by line in c++


I am trying to read a text file filled with individual hex values formatted like this:

0c 10 00 04 20 00 09 1a 00 20

What I would like is to read them in, convert to binary, then store in a vector. I would like my print statement to output like this:

00001100
00010000
00000000
00000100
00100000
00000000
00001001
00011010
00000000
00100000

I thought I was reading my file correctly but I can only seem to get the first hex value from each line. For example: I can only read 0c before getting the next line and so forth. If someone could tell me what I am doing wrong that would be great. Here is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <bitset>

using namespace std;

vector<bitset<8> > memory(65536);

int main () {

    string hex_line;
    int i = 0;
    ifstream mem_read;

    //Read text file
    mem_read.open("Examplefile.txt");

    if(mem_read.is_open()){

        //read then convert to binary
        while(getline(mem_read, hex_line)){

            unsigned hex_to_bin;
            stringstream stream_in;

            cout << hex_line << '\n';
            stream_in<< hex << hex_line;
            stream_in >> hex_to_bin;

            memory[i] = hex_to_bin;
            i++;
        }
    }else{
        cout << "File Read Error";
    }

    //print binaries
    for(int j = 0; j < i; j++){
        cout << memory[j] << '\n';
    }

    mem_read.close();

    return 0;
}

Solution

  • You are only feeding one token into the string stream: stream_in << hex_line!

    Your inner loop should look like this:

    while (std::getline(mem_read, hex_line))
    {
        istringstream stream_in(hex_line);
    
        for (unsigned hex_to_bin; stream_in >> hex >> hex_to_bin; )
        {
            memory[i] = hex_to_bin;
            i++;
        }
    }
    

    In fact, your entire code could be reduced in size quite a bit:

    #include <bitset>    // for std::bitset
    #include <fstream>   // for std::ifstream
    #include <iostream>  // for std::cout
    #include <iterator>  // for std::istream_iterator
    #include <sstream>   // for std::istringstream
    #include <string>    // for std::getline and std::string
    #include <vector>    // for std::vector
    
    std::vector<std::bitset<8>> memory;
    
    int main()
    {
        memory.reserve(65536);
        std::ifstream mem_read("Examplefile.txt");
    
        for (std::string hex_line; std::getline(mem_read, hex_line); )
        {
            std::istringstream stream_in(hex_line);
            stream_in >> std::hex;
            memory.insert(memory.end(),
                          std::istream_iterator<unsigned int>(stream_in), {});
        }
    
        for (auto n : memory) { std::cout << n << '\n'; }
    }