Lua 中 number 轉換各種進制,以及string串轉number
阿新 • • 發佈:2017-12-11
target 以及 .net pow number char table har tail
原文地址:http://blog.csdn.net/david_dai_1108/article/details/71699449
1 --region : NumConvert.lua 2 --Date : 2017-5-11 3 --Author : david 4 5 -- Bin 2 6 -- Oct 8 7 -- Dec 10 8 -- Hex 16 9 10 local _convertTable = { 11 [0] = "0", 12 [1] = "1", 13 [2] = "2", 14 [3] = "3", 15 [4] = "4", 16 [5] = "5", 17 [6] = "6", 18 [7] = "7", 19 [8] = "8", 20 [9] = "9", 21 [10] = "A", 22 [11] = "B", 23 [12] = "C", 24 [13] = "D", 25 [14] = "E", 26 [15] = "F", 27 [16] = "G", 28 } 29 30 local function GetNumFromChar(char) 31 for k, v in pairs(_convertTable) do32 if v == char then 33 return k 34 end 35 end 36 return 0 37 end 38 39 local function Convert(dec, x) 40 41 local function fn(num, t) 42 if(num < x) then 43 table.insert(t, num) 44 else 45 fn( math.floor(num/x), t) 46table.insert(t, num%x) 47 end 48 end 49 50 local x_t = {} 51 fn(dec, x_t, x) 52 53 return x_t 54 end 55 56 function ConvertDec2X(dec, x) 57 local x_t = Convert(dec, x) 58 59 local text = "" 60 for k, v in ipairs(x_t) do 61 text = text.._convertTable[v] 62 end 63 return text 64 end 65 66 function ConvertStr2Dec(text, x) 67 local x_t = {} 68 local len = string.len(text) 69 local index = len 70 while ( index > 0) do 71 local char = string.sub(text, index, index) 72 x_t[#x_t + 1] = GetNumFromChar(char) 73 index = index - 1 74 end 75 76 local num = 0 77 for k, v in ipairs(x_t) do 78 num = num + v * math.pow(x, k - 1) 79 end 80 return num 81 end 82 83 --endregion
Lua 中 number 轉換各種進制,以及string串轉number