Understanding how this works


New Member
I'm currently learning C++ at my school and we got a assignment to translate binary to ASCII.

Me and my friend found this code here on this site.
#include <bitset>
#include <fstream>

int main()
  std::ofstream fout("ASCII.txt");
  std::ifstream fin("Binary.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;
Could someone with a bit of spare-time explain more in detail what this means? We do understand "fstream" and how he reads the files. But bitsets is a little blurry, and we can't find any GOODGOOD tutorial on how it works, also what happens during the -for and -while loops. Thanks!


Thành viên BQT
The code opens two files:

ASCII.txt is opened for writing via the ofstream class instance, fout

Binary.txt is opened for reading via the ifstream class instance, fin

bitset is simply an array of bits. oc is a bitset of 8 bits, effectively 1 byte.

The while loop proceeds like this:

  • fin >> ic: read a character from fin (Binary.txt) and copy into ic (presumably this is either a '0' or '1' char.
  • ic - '0': Convert the ascii char read above into ic directly into a number 0 or 1 by subtracting from the ascii value of the character '0'.
  • oc[--i] = decrement i and then pack the 0 or 1 bit into the bitset at position i
  • fout << static_cast<char>(oc.to_ulong());: Every 8th iteration through the loop, a the bitset is now full and is a complete byte. Convert it back to an integer, cast to "char" and write the character back to fout (ASCII.txt). There's a lot going on in this statement.
  • the loop continues until there are no more bytes to read from fin (Binary.txt)