Algorithm4.2.1Read hexadecimal value from keyboard
\(value = 0\)

While more characters
shift \(value\) left four bits
\(temp = \) new character converted to int
\(value = value + temp\)
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.
\(value = 0\)
While more characters
shift \(value\) left four bits
\(temp = \) new character converted to int
\(value = value + temp\)
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 fourbit 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 fourbit 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 rightmost 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.
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