[英]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?? c++ 中是否有内置函数可以从用户那里获取十进制输入并将其转换为十六进制,反之亦然? 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
参考:
std::hex
, std::stringstream
Many compilers support the itoa
function (which appears in the POSIX standard but not in the C or C++ standards).许多编译器支持
itoa
函数(它出现在 POSIX 标准中,但不在 C 或 C++ 标准中)。 Visual C++ calls it _itoa
. Visual C++ 将其
_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.当然,当值应该显示在更长的消息中时,将
%x
格式说明符与任何printf
函数一起使用是很好的。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.