lua之m进制转换为n进制-任意进制转换算法

够无聊的写这个,为防止需要的人也无聊一遍,写个吧

算法有n种,但是,咱们一种就够用了

 1 --数组倒序排列
 2 local function orderByDesc( input )
 3     local output = {}
 4     local count = #input
 5     while count > 0 do
 6         table.insert(output, input[count] )
 7         count = count -1 
 8     end
 9     return output
10 end
11 
12 --进制转换,英文不行只好用拼音
13 --@dec 10进制数据,好吧,只要是数字就呆以了
14 --@x 进制,最常见的当然是二、八、十六、进制
15 local function _Dec2X( dec, x )
16     --计算结果存储在这里
17     local new_number = {}
18 
19     --算法如下:
20         --9527 = 9*(10^3)+5*(10^2)+2*(10^1)+7*(10^0)
21         --7 = 9527%10, 2 = (9527-7)%100/100
22         --f(n) = (dec % (x^i) - f(n-1))/x
23         --f(0) = 0
24     --a参数代表第几位,返回是否继续
25     local function f( a )
26         assert(a >= 1)
27         local mod = dec % math.pow(x, a)
28         local last_mod = (a == 1) and 0 or assert(new_number[a-1])
29         new_number[a] = (mod - last_mod)/math.pow(x, a - 1)
30         --取整数部分
31         new_number[a] = math.modf(new_number[a])
32         return mod ~= dec
33     end
34     --该函数取得某位值
35     local i = 1
36     while f(i) do
37         i = i + 1
38     end
39     
40     return new_number
41 end
42 
43 --将某个数据转成X进制
44 --以 9527,10进制为例,{7, 2, 5, 9}
45 local function _numberTable2X(  number_tbl,x )
46     local result = 0
47     for i,v in ipairs(number_tbl) do
48         print(result,x, i, v)
49         result = result + v*math.pow(x, i - 1)
50     end
51     return result
52 end
53 
54 local function test_Dec2X ()
55     local kTestNumber = 9527
56     local n1 = _Dec2X(kTestNumber, 10)
57     -- table.foreach(n1, function ( _,v )
58     --     print(v)
59     -- end)
60     assert(kTestNumber == _numberTable2X(n1, 10))
61 end
62 test_Dec2X()

 

posted @ 2016-01-25 18:31  冷侃  阅读(1855)  评论(1编辑  收藏  举报