1 /***************************************************************************************************/
 2 /*  Copyright (C) 2008  Chipset                                                                    
 3 /*                                                                           
 4 /*  This program is free software: you can redistribute it and/or modify
 5 /*  it under the terms of the GNU Affero General Public License as
 6 /*  published by the Free Software Foundation, either version 3 of the
 7 /*  License, or (at your option) any later version.
 8 /*                                                                    
 9 /*  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 /*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 /*  GNU Affero General Public License for more details.
12 /*                                                                    
13 /*  You should have received a copy of the GNU Affero General Public License
14 /*  along with this program. If not, see <http://www.gnu.org/licenses/>.
15 /****************************************************************************************************/
16 
17 //把一个10进制数转换成任意进制的字符窜
18 #include <string>
19 std::string my_itoa(int num, int radix = 10)
20 {
21   if(0 == num)
22     return  std::string("0");
23 
24   if(radix > 16 || radix < 2//2~16进制,否则默认10进制
25     radix = 10;
26 
27   std::string str;
28   if(num < 0 && 10 == radix) //转化成十进制字符窜并且<0,需要考虑符号
29   {
30     num = -num;
31     str += '-';
32    }
33 
34   const std::string dstr("0123456789abcdef");
35   std::string t;             //t中存放转化成的字符窜,反序
36 
37   for(unsigned n = static_cast<unsigned>(num); n; n /= radix)
38     t += dstr[n % radix];    //把最低位转化成字符并附加到字符窜中
39 
40   str += std::string(t.rbegin(), t.rend()); //考虑可能是十进制而且有符号,然后正序组合
41   return str;
42 }
43 
44 //测试
45 #include <iostream>
46 #include <cstdlib>
47 #include <ctime>
48 int main()
49 {
50   std::srand(std::time(0));
51   const int L = -std::rand(), H = std::rand(); //测试范围,随机数[L, H)
52   const unsigned BIN = 2, HEX = 16 + 1;        //测试不同进制[2, 16]
53   //随机测试不同进制,但2进制必测
54   for(unsigned j = BIN; j < HEX; j += std::rand() % (HEX - BIN))
55   {
56     std::cout << "radix == " << j << ":\n";
57     for(int i = L; i < H; i += std::rand() % (H - L))
58       std::cout << my_itoa(i, j) << "[" << i << ']' << " ";
59     std::cout << "\n\n";
60   }
61 
62   std::system("pause");
63 }