在Lua中,我如何将包含IP地址的字符串转换为整数?
答案 0 :(得分:20)
local str = "127.0.0.1"
local o1,o2,o3,o4 = str:match("(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)" )
local num = 2^24*o1 + 2^16*o2 + 2^8*o3 + o4
答案 1 :(得分:0)
其他方法可能是:
local addr = "127.0.0.1"
local num = 0
addr:gsub("%d+", function(s) num = num * 256 + tonumber(s) end)
答案 2 :(得分:0)
我提供了两种解决方案。
解决方案1:
function ip2dec(ip) local i, dec = 3, 0; for d in string.gmatch(ip, "%d+") do dec = dec + 2 ^ (8 * i) * d; i = i - 1 end; return dec end
function dec2ip(decip) local divisor, quotient, ip; for i = 3, 0, -1 do divisor = 2 ^ (i * 8); quotient, decip = math.floor(decip / divisor), math.fmod(decip, divisor); if nil == ip then ip = quotient else ip = ip .. "." .. quotient end end return ip end
解决方案2:
http://bitop.luajit.org/install.html
http://bitop.luajit.org/download.html
https://github.com/fengpeiyuan/ipconv
package.path = package.path .. ";/home/balaji/lualib/bitopt.lua"
package.cpath = package.cpath .. ";/home/balaji/lualib/bit.so"
local bit = require("bitopt")
function dec2ip(dec) return bit:band(bit:rshift(dec, 24), 0xFF) .. "." .. bit:band(bit:rshift(dec, 16), 0xFF) .. "." .. bit:band(bit:rshift(dec, 8), 0xFF) .. "." .. bit:band(dec, 0xFF) end
function ip2dec(ip) local dec = 0; for d in string.gmatch(ip, "%d+") do dec = d + bit:lshift(dec, 8) end; return dec end