Search code examples
visual-c++huffman-codebitstring

breaking up a bitstring c++


ok so I'm trying to do a Huffman encoding/decoding project atm. I have all of the compression working and tried to put the bitstring as a byte onto an output file. So I made a sample code to test with a small example to see how that would work. With code below I can correctly output the first 8 bits ("11100011") but then second time around I get 16 bits ("110001010101010"). Could someone hint where I went wrong? Thank you very much ahead of time.

Given: string bitstring = "11100011110001010101010"; unsigned char byte = 0;

for (int i = 0; i < bitstring.length(); i += 8){
    string stringof8 = "";
    if (i + 8 < bitstring.length()){
        stringof8 = bitstring.substr(i, 8);
        cout << stringof8 << endl;
    }
    else{
        stringof8 = bitstring.substr(i);
        cout << stringof8 << endl;
    }
}

system("pause");

also I'm using visual studio.

*EDIT: Fixed


Solution

  • Check the definition of the substr parameters. Is the second parameter position or length?