zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    二维码生成:使用 JavaScript 库QRCode.js生成二维码
    VC++6.0远程调试(亲试成功)
    Linux同时安装python2和Python3
    Python打包-py2exe
    camera按键采集图像及waitKey的用法(转)
    ucos实时操作系统学习笔记——任务间通信(信号量)(转)
    STM32硬件IIC驱动设计(转)
    基于STM32F4移植W5500官方驱动库ioLibrary_Driver(转)
    USB基础知识概论(版本:v0.9.2)
    usb帧格式
  • 原文地址:https://www.cnblogs.com/linbc/p/5158327.html
Copyright © 2011-2022 走看看