template<class IntType> bool AtoI(WCHAR *sz, IntType *out) { int i = 0; bool sign = false; if (sz[i] == '-') { ++i; sign = true; } int base = 10; if(sz[i] == '0' && tolower(sz[i+1]) == 'x') { i += 2; base = 16; } else if (sz[i] == '0' && sz[i+1] != '/0') { ++i; base = 8; } IntType res = 0; int chars = 0; while (sz[i] != '/0') { WCHAR c = tolower(sz[i++]); if (c >= '0' && c <= '9') c = c - '0'; else if (c >= 'a' && c <= 'f') c = c - 'a' + 10; else return false; if (c >= base) return false; IntType res_sav = res; res *= (IntType)base; if (res / (IntType)base != res_sav) { // Overflow! return false; } res_sav = res; res += (IntType)c; if (res < res_sav) { // Overflow! return false; } ++chars; } if (chars == 0) return false; *out = sign ? -res : res; return true; }