Skip to main content
\(\newcommand{\doubler}[1]{2#1} \newcommand{\binary}{\mathtt} \newcommand{\hex}{\mathtt} \newcommand{\octal}{\mathtt} \newcommand{\prog}{\mathtt} \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
\(\hex{0}\) \(\hex{30}\) \(\hex{0000 0000}\)
\(\hex{1}\) \(\hex{31}\) \(\hex{0000 0001}\)
\(\hex{2}\) \(\hex{32}\) \(\hex{0000 0002}\)
\(\hex{3}\) \(\hex{33}\) \(\hex{0000 0003}\)
\(\hex{4}\) \(\hex{34}\) \(\hex{0000 0004}\)
\(\hex{5}\) \(\hex{35}\) \(\hex{0000 0005}\)
\(\hex{6}\) \(\hex{36}\) \(\hex{0000 0006}\)
\(\hex{7}\) \(\hex{37}\) \(\hex{0000 0007}\)
\(\hex{8}\) \(\hex{38}\) \(\hex{0000 0008}\)
\(\hex{9}\) \(\hex{39}\) \(\hex{0000 0009}\)
\(\hex{a}\) \(\hex{61}\) \(\hex{0000 000a}\)
\(\hex{b}\) \(\hex{62}\) \(\hex{0000 000b}\)
\(\hex{c}\) \(\hex{63}\) \(\hex{0000 000c}\)
\(\hex{d}\) \(\hex{64}\) \(\hex{0000 000d}\)
\(\hex{e}\) \(\hex{65}\) \(\hex{0000 000e}\)
\(\hex{f}\) \(\hex{66}\) \(\hex{0000 000f}\)
Table4.4.1Hexadecimal characters and corresponding int

For the characters \(\hex{0}\)—\(\hex{9}\) 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.

/* readHex.c
 * Asks user to enter a number in hexadecimal.
 * Bob Plantz - 26 July 2016
#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