在c ++中逐行读取单个十六进制值

时间:2014-10-25 14:46:04

标签: c++ vector binary hex bitset

我正在尝试读取一个文本文件,其中填充了格式如下的单个十六进制值:

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

我想要的是读取它们,转换为二进制,然后存储在向量中。我希望我的print语句输出如下:

00001100
00010000
00000000
00000100
00100000
00000000
00001001
00011010
00000000
00100000

我以为我正在正确阅读我的文件,但我似乎只能从每一行获得第一个十六进制值。例如:我只能在获取下一行之前读取0c,依此类推。如果有人能告诉我我做错了什么就会很棒。这是我的代码:

#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;
}

1 个答案:

答案 0 :(得分:1)

您只需将一个令牌输入字符串流:stream_in << hex_line

你的内循环应如下所示:

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++;
    }
}

事实上,整个代码的大小可能会有所减少:

#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'; }
}