1 /******************************************************************** 2 created: 2014/03/16 22:56 3 filename: main.cpp 4 author: Justme0 (http://blog.csdn.net/justme0) 5 6 purpose: C++ 中數串互轉、進制轉換的類 7 *********************************************************************/ 8 9 #define _CRT_SECURE_NO_WARNINGS 10 #include <iostream> 11 #include <string> 12 #include <cassert> 13 using namespace std; 14 15 /* 16 ** Int 類用於數的進制轉換及與字符串互轉,目前只支持非負整數 17 */ 18 class Int { 19 public: 20 /* 21 ** 用數構造,默認構造爲0 22 */ 23 Int(int i = 0) : num(i) {} 24 25 /* 26 ** 用字符串構造,radix 爲字符串中的數的進制,默認十進制 27 */ 28 Int(const string &s, int radix = 10) 29 : num(strtol(s.c_str(), NULL, radix)) {} 30 31 /* 32 ** 獲取整數值 33 */ 34 int to_int() const { 35 return num; 36 } 37 38 /* 39 ** 獲取字符串形式,可設定獲取值的進制數,默認爲十進制 40 */ 41 string to_str(int radix = 10) const { 42 char s[35]; // int 最大是31個1 43 return _itoa(num, s, radix); 44 } 45 46 private: 47 int num; 48 }; 49 50 int main(int argc, char **argv) { 51 assert(string("1110") == Int(14).to_str(2)); 52 assert(14 == Int("1110", 2).to_int()); 53 assert(20 == Int("6").to_int() + Int("14").to_int()); 54 assert(13 == Int(Int(1101).to_str(), 2).to_int()); 55 56 cout << "ok" << endl; 57 58 system("PAUSE"); 59 return 0; 60 }