Since our primary goal here is to study storage formats, we will concentrate on bit patterns. In this and the next two sections we will develop a program in C that allows a user to enter bit patterns in hexadecimal. The program will read the characters from the keyboard in ASCII code and convert them into the corresponding int storage format as shown in Algorithm 4.2.1.

This conversion algorithm involves manipulating data at the bit level. Each character read from the keyboard represents a hexadecimal digit. That is, each character is one of $\hex{0},\ldots, \hex{9}, \hex{a},\ldots,\hex{f}\text{.}$ (We assume that the user does not make mistakes.) Since a hexadecimal digit represents four bits, we need to shift the accumulated integer four bits to the left in order to make room for the new four-bit value.

You should recognize that shifting an integer four bits to the left multiplies it by 16. As you will see in Section 14.3 and Section 14.4, multiplication and division are complicated operations, and they can take a great deal of processor time. Using left/right shifts to effect multiplication/division by powers of two is very efficient. More importantly, the four-bit shift is more natural in this application.

The C/C++ operator for shifting bits to the left is <<.  1  For example, if x is an int, the statement

shifts the value in x four bits to the left, thus multiplying it by sixteen. Similarly, the C/C++ operator for shifting bits to the right is >>. So if x is an int, the statement

shifts the value in x three bits to the right, thus dividing it by eight. Note that the three right-most bits are lost, so this is an integer / (div) operation.

The program in Listing 4.2.2 illustrates the use of the C shift operators to multiply and divide by powers of two.

# Subsection4.2.1Exercises

##### 1

Enter the program in Listing 4.2.2 and get it to work. What is $17 \times 2^{14}\text{?}$ What is $17 / 2^{3}\text{?}$ Explain the results.

Hint Solution