How to Read Hex Number C++

How to Read Hex Number C++ thumbnail
C++ includes standard library methods to convert numerical values

The C++ standard libraries offer methods to read and convert numbers of various bases to any other base. C++ programmers often have to deal with files that use other numerical bases such as hexadecimal (base-16) and convert those values to decimal (or another number type). By using the "hex" and "dec" conversion operators, among others, the programmer can easily read and manipulate hexadecimal numbers.

Things You'll Need

  • Text Editor
  • C or C++ Compiler (G++)
Show More

Instructions

    • 1

      Enter the following skeleton code into the text editor:

      #include <iostream>

      using namespace std;

      int main(){

      int value;

      }

      In order to read values from the user, the C++ program will need the "iostream" library, using the standard (std) namespace. The standard namespace is also required for the hexadecimal conversion. "Value" will hold the user-entered number.

    • 2

      Convert the hexadecimal to decimal. Add the following code to the skeleton code in the text editor:

      cin >> hex >> value;

      cout << dec << value << endl;

      The "hex" operator signals that the value entered is hexadecimal, and the "dec" operator converts the hexadecimal number to a decimal, and save the decimal to the variable value. For example, if the user enters "1b," a hexadecimal number, the output of value will read "27" (its decimal equivalent).

    • 3

      Convert the hexadecimal to octal. Enter the following code into the text editor:

      cin >> hex >> value;

      cout << oct << value << endl;

      This code performs the same operation as the "dec" operator, only converting the hexadecimal value to octal (base-8) notation. It the hexadecimal value entered is still "lb" then the octal value returned will read "33." Compile the file with G++ (g++ filename.cpp) and run the resulting output file (a.out).

Related Searches:

References

  • Photo Credit Ablestock.com/AbleStock.com/Getty Images

Comments

Related Ads

Featured