我正在寻找一种方式来轻松地转换hex
(十六进制)到dec
(十进制)。我发现了一个简单的方法来做到这一点,如:转换十六进制到十进制
int k = 0x265;
cout << k << endl;
但随着我不能输入265
。反正它以这样的工作:
输入:265
输出:613
反正有做到这一点?
注:我已经试过:
int k = 0x, b;
cin >> b;
cout << k + b << endl;
,它不工作。
我正在寻找一种方式来轻松地转换hex
(十六进制)到dec
(十进制)。我发现了一个简单的方法来做到这一点,如:转换十六进制到十进制
int k = 0x265;
cout << k << endl;
但随着我不能输入265
。反正它以这样的工作:
输入:265
输出:613
反正有做到这一点?
注:我已经试过:
int k = 0x, b;
cin >> b;
cout << k + b << endl;
,它不工作。
好时,C的方式可能是这样的......
#include <stdlib.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("%X", n);
exit(0);
}
下面是使用字符串解决方案并将其转换ASCII码为十进制表格:
#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;
}
我用这个:
template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
std::stringstream ss;
ss << std::hex << hexValue;
ss >> result;
return !ss.fail();
}
std::cout << "Enter decimal number: " ;
std::cin >> input ;
std::cout << "0x" << std::hex << input << '\n' ;
如果您添加的输入,可以是一个布尔值或浮动或INT将被传递回INT主函数调用...
用函数模板,基于参数类型,C生成单独的函数来适当地处理每种类型的调用。所有函数模板定义都以关键字模板开头,后面跟着括号括起来的参数<和>。一个形式参数T用于要测试的数据类型。
考虑下面的程序,用户被要求输入一个整数然后一个浮点数,每个程序使用平方函数来确定平方。 使用基于参数类型的函数模板,C生成单独的函数来适当地处理每种类型的调用。所有函数模板定义都以关键字模板开头,后面跟着括号括起来的参数<和>。一个形式参数T用于要测试的数据类型。
考虑下面的程序,用户被要求输入一个整数然后一个浮点数,每个程序使用平方函数来确定平方。
#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
'printf(“%x”,k)'我猜 – Esailija
这个不清楚。 '0x265' **是十进制的** 613。你在期待什么? –
@Esailija我认为它将int转换为十六进制。 – zeulb