我有一个充满二进制值 (0-1) 的文本,我正在尝试将其转换为 ASCII,我编写了一个代码,但效果不佳,而且需要很长时间才能编写,这是一个部分内容:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
ofstream fout("C:\\test.txt",ios :: binary);
ifstream file("E:\\mnmn.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
while((content[i] == '0')
&& (content[i+1] == '0')
&& (content[i+2] == '0')
&& (content[i+3] == '0')
&& (content[i+4] == '0')
&& (content[i+5] == '0')
&& (content[i+6] == '0')
&& (content[i+7] == '0')
{
char *data = "00000000";
char c = strtol(data, 0, 2);
fout<<c;
}
}
}
}
我必须对所有值执行相同的操作,即使我这样做了,程序也会重复这些值,因为 0 和 1 之间没有任何空格连接,难道没有更好的方法来转换它吗?
正文包含:
00001111101010001001010101110
等..
最佳答案
GCC 4.8.2:g++ -Wall -Wextra -std=c++11 read-01.cpp
#include <bitset>
#include <fstream>
int main() {
std::ofstream fout("test.txt");
std::ifstream fin("mnmn.txt");
char ic;
std::bitset<8> oc;
int i = 8;
while (fin >> ic) {
oc[--i] = ic - '0';
if (0 == i) {
fout << static_cast<char>(oc.to_ulong());
i = 8; } }
return 0; }
关于c++ - 将二进制转换为 ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22971794/