Search code examples
c++fileunsigned

Writing unsigned char into an output file


this might be a simple question but I'm not sure why I'm not getting it right. I have unsigned char buf of which I need to write its data to an output file f_out. when I write as following:

f_out << buf;

I get correct data.

However I want to write the data line by line, 32 bit (char) in a line as the data is binary numbers. I have used the following but I got totally different data:

for (int i = 1; i < Buff_size; i++) {
        for (int j = 1; j <= 32; j++) {
            f_out << buf[i];
        }
        f_out << endl;
    }

Solution

  • In the code as you have it, the following loop:

    for (int j = 1; j <= 32; j++) {
        f_out << buf[i];
    }
    

    will write each element of the array 32 times on each line!

    If what you want to do is to write each element only once but so that there are 32 elements per line, you need something like this:

    int i, j;
    for (i = 0, j = 0; i < Buff_size; i++) {
        f_out << buf[i];
        if (++j == 32) { // 32 done ...
            f_out << endl; // ... write newline
            j = 0;         // ... and reset count
        }
        else f_out << " "; // Stay on same line - but insert a space
    }
    if (j != 0) f_out << endl; // If we have 'leftover' buffer
    

    Feel free to ask for further explanation and/or clarification.