简体   繁体   中英

Decimal to hex conversion c++ built-in function

Is there a built-in function in c++ that would take a decimal input from a user and convert it to hex and vice versa?? I have tried it using a function I've written but I was wondering if there is a built-in one to minimize the code a little bit. Thanks in advance.

Decimal to hex :-

std::stringstream ss;
ss<< std::hex << decimal_value; // int decimal_value
std::string res ( ss.str() );

std::cout << res;

Hex to decimal :-

std::stringstream ss;
ss  << hex_value ; // std::string hex_value
ss >> std::hex >> decimal_value ; //int decimal_value

std::cout << decimal_value ;

Ref: std::hex , std::stringstream

Many compilers support the itoa function (which appears in the POSIX standard but not in the C or C++ standards). Visual C++ calls it _itoa .

#include <stdlib.h>

char hexString[20];
itoa(value, hexString, 16);

Note that there is no such thing as a decimal value or hex value. Numeric values are always stored in binary. Only the string representation of the number has a particular radix (base).

Of course, using the %x format specifier with any of the printf functions is good when the value is supposed to be shown in a longer message.

#include <iostream>
using namespace std;

int DecToHex(int p_intValue)
{
    char *l_pCharRes = new (char);
    sprintf(l_pCharRes, "%X", p_intValue);
    int l_intResult = stoi(l_pCharRes);
    cout << l_intResult<< "\n";
    return l_intResult;
}

int main()
{
    int x = 35;
    DecToHex(x);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM