(Packing Characters into Unsigned Integers) The left-shift operator can be used to pack two character values into a two-byte unsigned integer variable. Write a program that inputs two charac- ters from the keyboard and passes them to function packCharacters. To pack two characters into an unsigned integer variable, assign the first character to the unsigned variable, shift the unsigned variable

left by 8 bit positions and combine the unsigned variable with the second character using the bitwise inclusive-OR operator. The program should output the characters in their bit format before and after they’re packed into the unsigned integer to prove that they’re in fact packed cor- rectly in the unsigned variable.

What will be an ideal response?

```
#include
#include
using namespace std;

unsigned packCharacters( char, char );
void displayBits( unsigned );

int main()
{
char a;
char b;
unsigned result;

cout << "Enter two characters: ";
cin >> a >> b;

cout << "\n\'" << a << '\'' << " in bits as an unsigned integer is:\n";
displayBits( a );

cout << '\'' << b << '\'' << " in bits as an unsigned integer is:\n";
displayBits( b );

result = packCharacters( a, b );

cout << "\n\'" << a << '\'' << " and " << '\'' << b << '\''
<< " packed in an unsigned integer:\n";
displayBits( result );
return 0;
} // end main
// pack two character value into unsigned integer
unsigned packCharacters( char x, char y )
{
unsigned pack = x;
pack <<= 8; // left shift assignment operator
pack |= y; // bitwise exclusive-OR operator
return pack;
} // end function packCharacters

// display the bits in value
void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1 << SHIFT;

cout << setw( 7 ) << value << " = ";

for ( unsigned c = 1; c <= SHIFT + 1; c++ )
{
cout << ( value & MASK ? '1' : '0' );
value <<= 1;

if ( c % 8 == 0 ) // output a space after 8 bits
cout << ' ';
} // end for

cout << endl;
} // end function displayBits
```
Enter two characters: J K
'J' in bits as an unsigned integer is:
74 = 00000000 00000000 00000000 01001010
'K' in bits as an unsigned integer is:
75 = 00000000 00000000 00000000 01001011
'J' and 'K' packed in an unsigned integer:
19019 = 00000000 00000000 01001010 01001011

Computer Science & Information Technology

You might also like to view...

The Double paragraph spacing format includes ________ spacing after and double line spacing

A) 0 pt B) 4 pt C) 6 pt D) 8 pt

Computer Science & Information Technology

How are folders represented in a package?

What will be an ideal response?

Computer Science & Information Technology