Lua 中 number 转换各种进制,以及string串转number

时间:2021-12-21 15:30:39

原文地址:http://blog.csdn.net/david_dai_1108/article/details/71699449

 --region : NumConvert.lua
--Date : --
--Author : david -- Bin
-- Oct
-- Dec
-- Hex local _convertTable = {
[] = "",
[] = "",
[] = "",
[] = "",
[] = "",
[] = "",
[] = "",
[] = "",
[] = "",
[] = "",
[] = "A",
[] = "B",
[] = "C",
[] = "D",
[] = "E",
[] = "F",
[] = "G",
} local function GetNumFromChar(char)
for k, v in pairs(_convertTable) do
if v == char then
return k
end
end
return
end local function Convert(dec, x) local function fn(num, t)
if(num < x) then
table.insert(t, num)
else
fn( math.floor(num/x), t)
table.insert(t, num%x)
end
end local x_t = {}
fn(dec, x_t, x) return x_t
end function ConvertDec2X(dec, x)
local x_t = Convert(dec, x) local text = ""
for k, v in ipairs(x_t) do
text = text.._convertTable[v]
end
return text
end function ConvertStr2Dec(text, x)
local x_t = {}
local len = string.len(text)
local index = len
while ( index > ) do
local char = string.sub(text, index, index)
x_t[#x_t + ] = GetNumFromChar(char)
index = index -
end local num =
for k, v in ipairs(x_t) do
num = num + v * math.pow(x, k - )
end
return num
end --endregion