(Unpacking Characters from Unsigned Integers) Using the right-shift operator, the bitwise AND operator and a mask, write function unpackCharacters that takes the unsigned integer from Exercise 22.11 and unpacks it into two characters. To unpack two characters from an unsigned two- byte integer, combine the unsigned integer with the mask 65280 (11111111 00000000) and right- shift the result 8
bits. Assign the resulting value to a char variable. Then, combine the unsigned in- teger with the mask 255 (00000000 11111111). Assign the result to another char variable. The pro- gram should print the unsigned integer in bits before it’s unpacked, then print the characters in bits to confirm that they were unpacked correctly.
What will be an ideal response?
```
#include
#include
using namespace std;
// prototypes
void unpackCharacters( char * const, char * const, unsigned );
void displayBits( unsigned );
int main()
{
char a;
char b;
unsigned packed = 16706;
cout << "The packed character representation is:\n";
displayBits( packed );
// demonstrate unpacking of characters
unpackCharacters( &a, &b, packed );
cout << "\nThe unpacked characters are \'" << a << "\' and \'" << b
<< "\'\n";
displayBits( a );
displayBits( b );
return 0;
} // end main
// take apart the characters
void unpackCharacters( char * const aPtr, char * const bPtr,
unsigned pack )
{
unsigned mask1 = 65280;
unsigned mask2 = 255;
*aPtr = static_cast< char >( ( pack & mask1 ) >> 8 );
*bPtr = static_cast< char >( pack & mask2 );
} // end function unpackCharacters
// display the bits of 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 )
cout << ' ';
} // end for
cout << endl;
} // end function displayBits
```
The packed character representation is:
16706 = 00000000 00000000 01000001 01000010
The unpacked characters are 'A' and 'B'
65 = 00000000 00000000 00000000 01000001
66 = 00000000 00000000 00000000 01000010
You might also like to view...
Most modems include fallback capability to lower speed standards.
a. True b. False
The prefix ____ is used for representing a thousand trillion.
A. tera- B. exa- C. giga- D. peta-
What is an FDF file, and how do you create one?
What will be an ideal response?
The ____ attribute allows you to specify how many columns the column group should have.
A. cols B. span C. align D. width