Convert a hexadecimal number into decimal c++
To convert a hexadecimal number into decimal in C++, you can use the std::stoi
function from the <string>
library. Here's an example:
#include <iostream>
#include <string>
int main() {
std::string hexNumber = "1A"; // the hexadecimal number
int decimalNumber = std::stoi(hexNumber, nullptr, 16); // convert hexadecimal to decimal
std::cout << "Decimal number: " << decimalNumber << std::endl;
return 0;
}
Let's break down the code and explain each step:
- Include the necessary libraries:
#include <iostream>
#include <string>
We include the <iostream>
library for input and output operations and the <string>
library for string manipulation.
- Define the hexadecimal number:
std::string hexNumber = "1A";
We define the hexadecimal number as a string. In this example, the hexadecimal number is "1A".
- Convert hexadecimal to decimal:
int decimalNumber = std::stoi(hexNumber, nullptr, 16);
We use the std::stoi
function to convert the hexadecimal number to decimal. The function takes three arguments: the hexadecimal number as a string (hexNumber
), a pointer to the location where the function stopped parsing (nullptr
in this case), and the base of the number system (16 for hexadecimal).
- Display the decimal number:
std::cout << "Decimal number: " << decimalNumber << std::endl;
We use the std::cout
object to display the decimal number on the console.
- Return 0:
return 0;
This statement ends the main
function and returns 0 to indicate successful execution of the program.
By following these steps, you can convert a hexadecimal number into decimal in C++.