1

Hi I just wrote a program for Huffman Encoding in c++, where I take a text file, encode it in the form of 0's and 1's, and save that as another text file. However, this does not solve my purpose as it is taking even more space.

So I want to know how do I convert a text file containing these 0'S & 1's to a binary format.

Thank You in advance. :)

user3535581
  • 39
  • 1
  • 3
  • 1
    Use bit logic for that. Bit shift (<<), bitwise and (&), and counting to 8 (or 32) – Bgie Apr 15 '14 at 15:20
  • You are likely saving as ASCII "1" and ASCII "0" which themselves take up as many bits as any other character, you want to save to straight bits, but may need to see some code to demonstrate the problem you are seeing. – Kevin DiTraglia Apr 15 '14 at 15:22

1 Answers1

1

You can loop the text, each iteration read 8 chars from the text, convert this number to a single BYTE and write this byte to a file with ios::binary

Update:This might require you to know if your machine is little/big endian, depending on how you convert to BYTE

ZivS
  • 2,094
  • 2
  • 27
  • 48
  • Well I got the logic which you explained, but I'm not really clear about how to convert 8bytes char into a single byte. Also, I have a little knowledge about Endian concept. Could you maybe provide some link where this is explained? Thanks a lot. – user3535581 Apr 15 '14 at 16:30
  • You can use `strtol` for the conversion, this is an example of how: `char* binStr; long binary = strtol(binStr, NULL, 2); //32 chars, not 8 as I suggested` But please read about strtol as it can parse through your entire text with one loop. Also read [here](http://stackoverflow.com/questions/701624/difference-between-big-endian-and-little-endian-byte-order) about endians (or go to Wikipedia) – ZivS Apr 15 '14 at 17:02