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.

Algorithm 4.2.1 will read a hexadecimal value from the keyboard and convert it into the corresponding int storage format. It assumes that each character is in ASCII code.

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.5 and Section 14.6, 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 <<. For example, if x is an int, the statement

x = x << 4;


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

x = x >> 3;


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.