34 lines
946 B
Text
34 lines
946 B
Text
local fmt = require "fmt"
|
|
|
|
local function to_octets(n)
|
|
local s = fmt.bin(n)
|
|
local le = #s
|
|
local r = le % 7
|
|
local d = le // 7
|
|
if r > 0 then
|
|
d += 1
|
|
s = fmt.lpad(s, 7 * d, "0")
|
|
end
|
|
local chunks = s:split(""):chunk(7):map(|ch| -> ch:concat(""))
|
|
local last = "0" .. chunks:back()
|
|
s = chunks:slice(1, -2):map(|ch| -> "1" .. ch):concat("") .. last
|
|
return s:split(""):chunk(8):map(|ch| -> tonumber(ch:concat(""), 2))
|
|
end
|
|
|
|
local function from_octets(octets)
|
|
local s = ""
|
|
for octets as oct do
|
|
local bin = fmt.bin(oct)
|
|
bin = fmt.lpad(bin, 7, "0")
|
|
s ..= bin:sub(-7)
|
|
end
|
|
return tonumber(s, 2)
|
|
end
|
|
|
|
local tests = {2097152, 2097151}
|
|
for tests as test do
|
|
local octets = to_octets(test)
|
|
local display = octets:mapped(|oct| -> "Ox" .. string.format("%02x", oct))
|
|
io.write($"{test} -> {fmt.swrite(display, " ", "")} -> ")
|
|
print(from_octets(octets))
|
|
end
|