Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Converting Hexadecimal to Decimal

I'm looking for a way to convert hex(hexadecimal) to dec(decimal) easily. I found an easy way to do this like :

int k = 0x265;
cout << k << endl;

But with that I can't input 265. Is there anyway for it to work like that:

Input: 265

Output: 613

Is there anyway to do that ?

Note: I've tried:

int k = 0x, b;
cin >> b;
cout << k + b << endl;

and it doesn't work.

like image 396
zeulb Avatar asked Jun 14 '12 10:06

zeulb


People also ask

How do you convert hexadecimal to decimal?

Given hexadecimal number is 7CF. To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number. From this, the rule can be defined for the conversion from hex numbers to decimal numbers.

What does C equal in hexadecimal?

Facts of Hexadecimal Number System A, B, C, D, E, F are single bit representations of 10, 11, 12, 13, 14 and 15 respectively.

Does C support hexadecimal?

In C programming language, hexadecimal value is represented as 0x or 0X and to input hexadecimal value using scanf which has format specifiers like %x or %X.


1 Answers

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    int x, y;
    std::stringstream stream;

    std::cin >> x;
    stream << x;
    stream >> std::hex >> y;
    std::cout << y;

    return 0;
}
like image 162
smichak Avatar answered Oct 12 '22 04:10

smichak