c++ - 将二进制转换为 ASCII

标签 c++

我有一个充满二进制值 (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/

相关文章:

c++ - 在 iOS 目标低于 5.0 的 iPhone 应用程序中使用 C++

c++ - 为 vector : template parameters not deducible in partial specialization 定义散列

c++ - 将 std::wstring 转换为 cstring 是否安全?

c++ - 如何在使用 GCC 时使用 __align__ 中的大小进行缓存对齐?

c++ - 如何为完成端口创建多个线程?

c++ - 取消引用被转换为双指针的指针

c++ - 我如何模拟在 gmock 中存储为 unique_ptr 的对象?

c++ - 如何打印正在使用 LLDB 调试的 C/C++ 函数的内存地址和参数值?

c++ - 如何在异构容器上使用 boost::fusion::transform?

c++ - 什么是 __ext_vector_type__ 和 simd?