zeu*_*ulb 8 c++ algorithm hex decimal
我正在寻找一种方法将hex(十六进制)转换为dec(十进制).我找到了一个简单的方法,如:
int k = 0x265;
cout << k << endl;
Run Code Online (Sandbox Code Playgroud)
但随着我不能输入265.无论如何它是这样的:
输入: 265
输出: 613
反正有吗?
注意:我试过了:
int k = 0x, b;
cin >> b;
cout << k + b << endl;
Run Code Online (Sandbox Code Playgroud)
它不起作用.
smi*_*hak 19
#include <iostream>
#include <iomanip>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
hmj*_*mjd 11
使用std::hex操纵器:
#include <iostream>
#include <iomanip>
int main()
{
int x;
std::cin >> std::hex >> x;
std::cout << x << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
那么,C方式可能就像......
#include <stdlib.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("%X", n);
exit(0);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这是使用字符串并将其转换为带有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;
}
Run Code Online (Sandbox Code Playgroud)