## Exercises4.5Programming Exercise

###### 1.

Here is a program that simply reads characters from the keyboard until the user hits the enter (or return) key. Add code to the program so that it allows the user to enter up to a 32-bit integer in hexadecimal and converts the number to int format. Your algorithm should make use of the masking operation described above. The program should display the int in both hexadecimal and decimal format for the user. Assume that the user will not make mistakes.

/* readHex.c
* INCOMPLETE PROGRAM FOR EXERCISE.
* 2017-09-29: Bob Plantz
*/
#include <stdio.h>
#include <unistd.h>

int main(void)
{
int x;
unsigned char aChar;

printf("Enter an integer in hexadecimal: ");
fflush(stdout);

x = 0;                           // initialize result
read(STDIN_FILENO, &aChar, 1);   // get first character
while (aChar != '\n')            // look for return key
{
}

printf("You entered %#010x = %d (decimal)\n\n", x, x);

return 0;
}

Hint

Refer to Table 2.13.1 to see why the masking operation above works for the hex characters $\hex{0}\ldots\hex{9}\text{.}$ Study the bit patterns of the characters $\hex{a}\ldots\hex{f}$ and $\hex{A}\ldots\hex{F}\text{.}$ What value do you need to add to these characters before masking off the “ASCII part”?

Solution
/* convertHex.c
* then echoes it in hexadecimal and in decimal.
* Assumes that user does not make mistakes.
* 2017-09-29: Bob Plantz
*/

#include <stdio.h>
#include <unistd.h>

int main(void)
{
int x;
unsigned char aChar;

printf("Enter an integer in hexadecimal: ");
fflush(stdout);

x = 0;                          // initialize result
read(STDIN_FILENO, &aChar, 1);  // get first character
while (aChar != '\n') {        // look for return key
x = x << 4;                   // make room for next four bits
if (aChar > '9') {
aChar = aChar + 9;          // for 'gap' in hex
}
aChar = aChar & 0x0f;         // mask off ascii part
x = x + (int)aChar;           // insert in vacant space

The fflush(stdout); statement is required because output to stdout is line buffered.