十进制到十六进制转换 C++ 内置函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20034297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:52:49  来源:igfitidea点击:

Decimal to hex conversion c++ built-in function

c++hexdecimalbuilt-in

提问by user3002197

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.

c++ 中是否有内置函数可以从用户那里获取十进制输入并将其转换为十六进制,反之亦然?我已经使用我编写的函数进行了尝试,但我想知道是否有内置函数可以将代码最小化一点。提前致谢。

回答by P0W

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

回答by Ben Voigt

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

许多编译器支持该itoa函数(它出现在 POSIX 标准中,但不在 C 或 C++ 标准中)。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 %xformat specifier with any of the printffunctions is good when the value is supposed to be shown in a longer message.

当然,当值应该显示在更长的消息中时,将%x格式说明符与任何printf函数一起使用是很好的。

回答by Trilokesh Ranjan Pradhan

include

包括

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