Write the contents of the input file as a последовательность бит to another file.

That is, биты конвертировать в байты , and write to the output file

  • And how do you imagine binary code? And how do you imagine it in the file? And in the text? - Vladimir Martyanov
  • Specify whether the added data of the binary file should remain "as is" or their presentation changes according to some rules? - avp
  • Hmm, all files are essentially stored in memory as a sequence of zeros and ones. You need to view this sequence in a specific file, and output the result in a text document. It is implemented using the fstream and ios :: binary connections, just how? - user284832
  • one
    @logner And what's the problem? In reading of bytes, in transfer in string representation with the basis 2 or in an output in a file? - Vladimir Martyanov
  • You want to display the contents of the file in a brazen - bitwise? - Egor Randomize

3 answers 3

  //для одного символа using namespace std; const char c = 'f'; bitset<8> b(c); cout << b; // для строки const string s; vector< bitset<8> > v; copy(s.begin(), s.end(), back_inserter(v)); 

let the file contents be a string s or a vector of strings, then the question is resolved

    Understood. Opens a file of any format, reads the binary code and displays it in a text document binaryFileCode.txt .

     #include <iostream> #include <string> #include <fstream> #include <iterator> using namespace std; int main () { //читаем файл как бинарный ifstream fin("<имя файла или полный адрес файла>", ios::binary); //на случай ошибки чтения if (!fin) //вывод ошибки cout << "Ошибка! Невозможно прочесть файл." << endl; //если файл прочитан, то else { //записываем в переменную прочитанный файл string str((istreambuf_iterator<char>(fin)), istreambuf_iterator<char>()); //создаём объект для вывода в файл ofstream binaryFileCode ; //создаём файл, куда будем выводить данные binaryFileCode .open("binaryFileCode.txt"); //записываем в файл данные binaryFileCode << str; //закрываем файл binaryFileCode .close(); //выводим сообщение cout << "Успешно!"; } return 0; } 

      The program opens the file 1.txt , reads it, and writes "bits bytes" in 2.txt

       #include <iostream> #include <fstream> // подключаем файлы using namespace std; int main() { ifstream f("1.txt", ios::binary); ofstream o("2.txt", ios::binary); char ch; if (!f) { cout << "Error opening file!" << endl; system("pause"); return 0; } while (f.get(ch)) { for (int i = 7; i >= 0; i--) { o.write((((int)ch & (int)pow(2, i)) > 0 ? "1" : "0"),1); } } f.close(); o.close(); return 0; }