17

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.

Omer Dagan
  • 14,868
  • 16
  • 44
  • 60
zeulb
  • 637
  • 1
  • 7
  • 23

11 Answers11

26
#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;
}
SebastianWilke
  • 470
  • 1
  • 4
  • 15
smichak
  • 4,716
  • 3
  • 35
  • 47
16

Use std::hex manipulator:

#include <iostream>
#include <iomanip>

int main()
{
    int x;
    std::cin >> std::hex >> x;
    std::cout << x << std::endl;

    return 0;
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 1
    anyway to do this without using input ? cause i want to use the original input for something else – zeulb Jun 14 '12 at 10:38
  • 1
    @zeulb, not sure what you mean exactly. But you revert `cin` to use decimal by `std::cin >> std::dec;` – hmjd Jun 14 '12 at 10:42
  • i mean i want to use both hex and decimal on two different varible – zeulb Jun 14 '12 at 10:43
  • 1
    How the input was done (hex or decimal) doesn't have any influence on the internal representation of the int variable(s), so what?? Plz express yourself more clearly. Do you want to store the values from the stream to two variables within the same statement?? – πάντα ῥεῖ Jun 14 '12 at 10:48
  • like i use 'cin >> hex >> k;', then i input 265, now k value was 613. what i want is to store 265 on varible p. and 613 stay on variable k. sorry for my bad english. – zeulb Jun 14 '12 at 10:51
  • Your question had no variable `p`. This post answers the question you posted :( – Mooing Duck Sep 02 '22 at 15:27
6

Well, the C way might be something like ...

#include <stdlib.h>
#include <stdio.h>

int main()
{
        int n;
        scanf("%d", &n);
        printf("%X", n);

        exit(0);
}
stefanl
  • 61
  • 1
6

Here is a solution using strings and converting it to decimal with ASCII tables:

#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
{
    unsigned long result = 0;
    for (int i=0; i<hex.length(); i++) {
        if (hex[i]>=48 && hex[i]<=57)
        {
            result += (hex[i]-48)*pow(16,hex.length()-i-1);
        } else if (hex[i]>=65 && hex[i]<=70) {
            result += (hex[i]-55)*pow(16,hex.length( )-i-1);
        } else if (hex[i]>=97 && hex[i]<=102) {
            result += (hex[i]-87)*pow(16,hex.length()-i-1);
        }
    }
    return result;
}

int main(int argc, const char * argv[]) {
    string hex_str;
    cin >> hex_str;
    cout << hex2dec(hex_str) << endl;
    return 0;
}
Christos
  • 61
  • 1
  • 2
1

I use this:

template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
    std::stringstream ss;
    ss << std::hex << hexValue;
    ss >> result;

    return !ss.fail();
}
Dmytro
  • 1,290
  • 17
  • 21
1
    std::cout << "Enter decimal number: " ;
    std::cin >> input ;

    std::cout << "0x" << std::hex << input << '\n' ;

if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...

With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square. With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.

#include <iostream>
 using namespace std;
template <class T>      // function template
T square(T);    /* returns a value of type T and accepts                  type T     (int or float or whatever) */
  void main()
{
int x, y;
float w, z;
cout << "Enter a integer:  ";
cin >> x;
y = square(x);
cout << "The square of that number is:  " << y << endl;
cout << "Enter a float:  ";
cin >> w;
z = square(w);
cout << "The square of that number is:  " << z << endl;
}

template <class T>      // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}

Here is the output:

Enter a integer:  5
The square of that number is:  25
Enter a float:  5.3
The square of that number is:  28.09
0

This should work as well.

#include <ctype.h>
#include <string.h>

template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
    if (!Hexstr)
        return false;
    if (Overflow)
        *Overflow = false;

    auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
    size_t len = strlen(Hexstr);
    T result = 0;

    for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
    {
        if (between(Hexstr[i], '0', '9'))
            result = result << 4 ^ Hexstr[i] - '0';
        else if (between(tolower(Hexstr[i]), 'a', 'f'))
            result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
        offset -= 4;
    }
    if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
        *Overflow = true;
    return result;
}

The 'Overflow' parameter is optional, so you can leave it NULL.

Example:

auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);
guila
  • 33
  • 5
0

only use:

cout << dec << 0x;

0

If you have a hexadecimal string, you can also use the following to convert to decimal

int base = 16;
std::string numberString = "0xa";
char *end; 
long long int number;

number = strtoll(numberString.c_str(), &end, base);
0

I think this is much cleaner and it also works with your exception.

#include <iostream>
using namespace std;
using ll = long long;
int main ()
{
    ll int x;
    cin >> hex >> x;
    cout << x;
}
0

std::stoi, stol, stoul, stoull can convert to different number systems

long long hex2dec(std::string hex)
{
    std::string::size_type sz = 0;
    try
    {
        hex = "0x"s + hex;
        return std::stoll(hex, &sz, 16);
    }
    catch (...)
    {
        return 0;
    }
}

and similar if you need return string

std::string hex2decstr(std::string hex)
{
    std::string::size_type sz = 0;
    try
    {
        hex = "0x"s + hex;
        return std::to_string(std::stoull(hex, &sz, 16));
    }
    catch (...)
    {
        return "";
    }
}

Usage:

std::string converted = hex2decstr("16B564");
Man
  • 1
  • 2