vector - Reading individual hex values line by line in c++ -
vector - Reading individual hex values line by line in c++ -
i trying read text file filled individual hex values formatted this:
0c 10 00 04 20 00 09 1a 00 20
what read them in, convert binary, store in vector. print statement output this:
00001100 00010000 00000000 00000100 00100000 00000000 00001001 00011010 00000000 00100000
i thought reading file correctly can seem first hex value each line. example: can read 0c before getting next line , forth. if tell me doing wrong great. here 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 = 0; ifstream mem_read; //read text file mem_read.open("examplefile.txt"); if(mem_read.is_open()){ //read convert 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(); homecoming 0; }
you feeding 1 token string stream: stream_in << hex_line
!
your inner loop should this:
while (std::getline(mem_read, hex_line)) { istringstream stream_in(hex_line); (unsigned hex_to_bin; stream_in >> hex >> hex_to_bin; ) { memory[i] = hex_to_bin; i++; } }
in fact, entire code reduced in size quite bit:
#include <bitset> // std::bitset #include <fstream> // std::ifstream #include <iostream> // std::cout #include <iterator> // std::istream_iterator #include <sstream> // std::istringstream #include <string> // std::getline , std::string #include <vector> // std::vector std::vector<std::bitset<8>> memory; int main() { memory.reserve(65536); std::ifstream mem_read("examplefile.txt"); (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), {}); } (auto n : memory) { std::cout << n << '\n'; } }
c++ vector binary hex bitset
Comments
Post a Comment