Docsity

C++ Programming Exercise: Outputting Integers as 8-bit Strings, Study notes of Computer Science

Toggle sidebar
bg1
Exercise 10/14/03 and 10/16/03
1. Write a C++ program that outputs integers in the range of 0 and 255, using a for loop. The numbers
should be output 8 numbers on each line, with proper spacing.
2. Extend and modify the above program so as to output each of the integers in the range [0, 255] as an 8-bit
string (instead of an integer), using the following function:
void printbits ( int i )
// This function takes an integer i, where 0 <= i < 256, and
// outputs it in the form of an 8-bit string.
// Precondition: Parameter i is an integer with the range of [0, 255].
// Postcondition: The binary representation of i is output.
{
string bits[16] = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};
cout << bits[i/16] << bits[i%16] << " ";
}
Note that you would need to include the <string> header file in order to be able to declare variables of
“type” string in the printbits function.

Partial preview of the text

Download C++ Programming Exercise: Outputting Integers as 8-bit Strings and more Study notes Computer Science in PDF only on Docsity!

Exercise 10/14/03 and 10/16/

1. Write a C++ program that outputs integers in the range of 0 and 255, using a for loop. The numbers

should be output 8 numbers on each line, with proper spacing.

2. Extend and modify the above program so as to output each of the integers in the range [0, 255] as an 8-bit

string (instead of an integer), using the following function:

void printbits ( int i ) // This function takes an integer i, where 0 <= i < 256, and // outputs it in the form of an 8-bit string. // Precondition: Parameter i is an integer with the range of [0, 255]. // Postcondition: The binary representation of i is output. { string bits[16] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; cout << bits[i/16] << bits[i%16] << " "; }

Note that you would need to include the header file in order to be able to declare variables of

“type” string in the printbits function.