Decimal to hex conversion C ++ inline function

Is there a built-in function in C ++ that will accept decimal input from the user and convert it to hexadecimal and vice versa? I tried this with the function I wrote, but I was wondering if there is any built-in to slightly reduce the code. Thanks in advance.

+6
source share
3 answers

Decimal value in hex: -

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

Hexadecimal to decimal: -

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

Link: std::hex , std::stringstream

+18
source

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 a hexadecimal value. Numeric values ​​are always stored in binary format. Only the string representation of a number has a specific base (base).

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

+6
source

turn on

using the std namespace;

 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; } 
-1
source

Source: https://habr.com/ru/post/958269/


All Articles