Skip to main content
\(\newcommand{\doubler}[1]{2#1} \newcommand{\binary}{\texttt} \newcommand{\hex}{\texttt} \newcommand{\octal}{\texttt} \newcommand{\prog}{\texttt} \newcommand{\lt}{ < } \newcommand{\gt}{ > } \newcommand{\amp}{ & } \)

Section4.4C/C++ Data Type Conversions

Now we are prepared to see how we can convert from the ASCII character code to the int format. The & operator works very nicely for the conversion. First, look at the comparison between each hexadecimal character and its corresponding integer value in Table 4.4.1.

Hex character ASCII code Corresponding int
0 \(\hex{30}\) \(\hex{0000 0000}\)
1 \(\hex{31}\) \(\hex{0000 0001}\)
2 \(\hex{32}\) \(\hex{0000 0002}\)
3 \(\hex{33}\) \(\hex{0000 0003}\)
4 \(\hex{34}\) \(\hex{0000 0004}\)
5 \(\hex{35}\) \(\hex{0000 0005}\)
6 \(\hex{36}\) \(\hex{0000 0006}\)
7 \(\hex{37}\) \(\hex{0000 0007}\)
8 \(\hex{38}\) \(\hex{0000 0008}\)
9 \(\hex{39}\) \(\hex{0000 0009}\)
a \(\hex{61}\) \(\hex{0000 000a}\)
b \(\hex{62}\) \(\hex{0000 000b}\)
c \(\hex{63}\) \(\hex{0000 000c}\)
d \(\hex{64}\) \(\hex{0000 000d}\)
e \(\hex{65}\) \(\hex{0000 000e}\)
f \(\hex{66}\) \(\hex{0000 000f}\)
Table4.4.1Hexadecimal characters and corresponding int

For the characters 09 the conversion from the ASCII value to an int value can be easily done with the code:

aChar = aChar & 0x0f;
anInt = (int)aChar;

where aChar is a char variable and anInt is an int variable. The & operation used this way is often called masking. The (int) operation type casts the value stored in aChar to be an int value, effectively extending it to be 32 bits.



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.

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

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

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

    x = 0;                           // initialize result
    read(STDIN_FILENO, &aChar, 1);   // get first character
    while (aChar != '\n')            // look for return key
        read(STDIN_FILENO, &aChar, 1);
    printf("You entered %#010x = %d (decimal)\n\n", x, x);

    return 0;
Hint Solution