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 }