Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract the 4 bytes of a 32bit int in lua

Tags:

lua

I have a lua function that converts ip addresses to 32 bit int

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

I would like to have the inverse function, i.e. get the 4 bytes from the int

like image 355
Max L. Avatar asked Nov 14 '14 23:11

Max L.


Video Answer


2 Answers

You can use bit or bit32 libraries (included in Lua 5.2+ and LuaJIT and available as modules for 5.1). You can also use the reverse operations to what you already have:

print(math.floor(num / 2^24), math.floor((num % 2^24) / 2^16),
  math.floor((num % 2^16) / 2^8), num % 2^8)
like image 56
Paul Kulchenko Avatar answered Oct 19 '22 10:10

Paul Kulchenko


Use string.unpack/pack to convert most primitive types to or from byte array (string in Lua).

like image 25
Itay Gal Avatar answered Oct 19 '22 08:10

Itay Gal