Skip to content

Instantly share code, notes, and snippets.

@Anaminus
Last active September 29, 2020 01:40
Show Gist options
  • Select an option

  • Save Anaminus/4d53fd85a010544c44f855e7bf59815e to your computer and use it in GitHub Desktop.

Select an option

Save Anaminus/4d53fd85a010544c44f855e7bf59815e to your computer and use it in GitHub Desktop.
UnwrapBase unwraps a number to a given base for a given number of digits.
-- UnwrapBase unwraps a number to a given base for a given number of digits.
--
-- Examples:
-- 3-digit decimal: UnwrapBase(42, 10, 3) -- 2, 4, 0
-- 8-bit binary: UnwrapBase(85, 2, 8) -- 1, 0, 1, 0, 1, 0, 1, 0
-- DWORD: UnwrapBase(0xDEADBEEF, 256, 4) -- 249, 190, 173, 222
--
local function UnwrapBase(value, base, length)
if not length then
length = math.ceil(math.log(value+1)/math.log(base))
end
local output = {}
for i = 0, (length or 1) - 1 do
output[i+1] = math.modf(value / base^i % base)
end
return unpack(output)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment