Skip to content

Instantly share code, notes, and snippets.

@Youka
Last active April 30, 2017 00:42
Show Gist options
  • Select an option

  • Save Youka/863e90871081180dfa61 to your computer and use it in GitHub Desktop.

Select an option

Save Youka/863e90871081180dfa61 to your computer and use it in GitHub Desktop.
Converter between byte string and number
-- Lua 5.1 or 5.2 table unpacker
local unpack = table.unpack or unpack
-- Bytes to unsigned integer
local function bton(s)
local bytes, n = {s:byte(1,-1)}, 0
for i=0, #s-1 do
n = n + bytes[1+i] * 256^i
end
return n
end
-- Unsigned integer to bytes
local function ntob(n, len)
local bytes = {}
for i=1, len do
bytes[i] = n % 256
n = math.floor(n / 256)
end
return string.char(unpack(bytes))
end
-- Test
print(
bton(ntob(32767, 2))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment