Converting a c style program to a c++

145 Views Asked by At

I have this C style program:

void showOneByteBinaryNumber( char c ) {
    for ( int i = 128; i >=1; i >>= 1 ) {
        // Fixed Typo - Replaced a ; with the correct {
        if ( c & i ) {
            printf( "1" );
        } else {
            printf( "0" );
        }
    }
}

int main() {
    for ( int i = 0; i < 256; i++ ) {
        printf( "%3d = ", i );
        showOneByteBinaryNumber( i );
        printf( "\n" );
     }

     return 0;
}

I then change my program to this:

void showOneByteBinaryNumber( char c ) {
    for ( int i = 128; i >= 1; i >>= 1 ) {
        if ( c & i ) {
            std::cout << 1;
        }
        else {
            std::cout << 0;
        }
    }
}

int main() {
    for ( int i = 0; i < 256; i++ ) {
        std::cout << "%3d = " << i;
        showOneByteBinaryNumber( i );
        std::cout << "\n";
    }

    return 0;
}

I should be expecting to see the table of binary values increasing from 0 to 255, however when I try to convert this to a c++ equivalent version using std::cout instead, I'm getting other digits that are not 0 or 1 in the output.

I'm not sure if the culprit is within the changed function or within the for loop within main. I'm not sure how to change the parameter for printf() "%3d"; to do the same with std::cout

1

There are 1 best solutions below

5
Francis Cugler On

It was RamandepPunia who provided the correct answer for me!

In this line of code:

printf( "%3d", i );

where I was trying to replace it with

std::cout << "%3d = " << i; // I did initially try std::setw( 3 ) but was giving wrong results;
std::cout << std::setw(3) << " = " << i;

His comment with the code:

std::cout << std::setw(3) << i << " = ";

Is what I was looking for and now the program gives me the correct results!

EDIT

After I got it working I did modify my function to this:

void showOneByteBinaryNumber( char c ) {
    for ( int i = 128; i >= 1; i >>= 1 ) {
        std::cout << ( (c & i) ? 1 : 0);
     }
}

However: David C. Rankin showed me this version as well

void showOneByteBinaryNumber( char c ) {
    for ( int i = 1 << 7; i; i >>= 1 ) {
        c & i ? std::cout << 1 : std::cout << 0;
    }
}