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