在c++中逐行读取单个十六进制值
Reading individual hex values line by line in c++
我正在尝试读取一个文本文件,该文件中填充了如下格式的单个十六进制值:
0c 10 00 04 20 00 09 1a 00 20
我想把它们读入,转换成二进制,然后存储在矢量中。我希望我的打印报表输出如下:
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;
}
您只向字符串流中馈送了一个令牌: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'; }
}
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 指向存储在字符串 c++ 中的十六进制
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 绝对编码器十六进制输入
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- C++17 十六进制浮点文字单精度后缀冲突?
- 如何在单个块中显示十六进制值
- 将十六进制单个文本字符转换为其值
- 在c++中逐行读取单个十六进制值