2010年9月7日 星期二

[C++] Hex string convert to integer with stringstream

Sometimes we need to convert hex string to integer.
Usually we will use this alrorithm.
char xtod(char c) {
if (c>='0' && c<='9') return c-'0';
if (c>='A' && c<='F') return c-'A'+10;
if (c>='a' && c<='f') return c-'a'+10;
return c=0; // not Hex digit
}
This is a conventional usage.
Tonight I found a question in CSDN, then I try to found a better solution.
In stackoverflow, I found this answer.
It is very nice.
#include <sstream>
#include <iostream>

int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "FF";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}

沒有留言:

張貼留言

Hello