Hex to Int
| ||
题目描述
Write a function that parses a hex number as a string into a decimal integer. The function is defined as follows.
int parseHex(const char * hexString)
For example, hexString "A5" is 165 (10*16+5=165). So, parseHex("A5") returns 165.
Your implementation of parseHex function should throw a runtime_error exception if the binaryString is not a hex string.
The main function is:
int main() { string s; while (cin >> s) { try { cout << parseHex(s) << endl; } catch (runtime_error &ex) { cout << ex.what() << endl; } } return 0; }
样例输入
10 fffffffF 9G3
样例输出
16 -1 Hex number format error
提示
You also NEED to submit the main() function. The hex numbers mentioned above must be considered astwo's complements of 32-bit numbers. (ffffffff)16, therefore, is less than 0, since its most significant bit is 1. | ||
|
#include
#include
#include
#include
using namespace std;
int parseHex(const char * const hexString)
{
int result=0; //...
int len = strlen(hexString);
int dec = 0;
for(int i=0; i
='0' && hexString[i]<='9')||(hexString[i]>='A' && hexString[i]<='F')||(hexString[i]>='a' && hexString[i]<='f')) { if(hexString[i]>='0' && hexString[i]<='9') dec=hexString[i]-'0'; else if(hexString[i]>='A' && hexString[i]<='F') dec=hexString[i]-'A'+10; else if(hexString[i]>='a' && hexString[i]<='f') dec=hexString[i]-'a'+10; result=16*result+dec; } else throw runtime_error("Hex number format error"); } return result; } int main() { string s; while (cin>>s) { try { cout << parseHex(s.c_str()) << endl; } catch (runtime_error &ex) { cout << ex.what() << endl; } } return 0; }