Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function chars(str)
- local pos = 1
- return function()
- if pos <= #str then
- local pos_was = pos
- pos = pos + 1
- return str:sub(pos_was, pos_was), pos_was
- end
- end
- end
- local function nybbles(byte)
- return bit.brshift(bit.band(0xF0, byte), 4), bit.band(0x0F, byte)
- end
- local function from_nybbles(hi, lo)
- return bit.bor(bit.blshift(hi, 4), lo)
- end
- local hexToColor = {}
- for n = 0, 15 do
- hexToColor[string.format("%x", n)] = 2 ^ n
- end
- local function log2(x)
- return math.log10(x) / math.log10(2)
- end
- local function decode_col(c)
- return log2(hexToColor[c] or 1)
- end
- local function split_pair(pair)
- return pair:sub(1, 1), pair:sub(2, 2)
- end
- local paint_encode = {}
- local function groups(str, l)
- local out, current = {}
- local pos = 1
- repeat
- current = str:sub(pos, pos + l - 1)
- pos = pos + l
- table.insert(out, current)
- until current == ""
- return out
- end
- function paint_encode.encode(str)
- local cols = ""
- for c in chars(str) do
- cols = cols .. string.format("%02x", string.byte(c))
- end
- local line_qty = math.sqrt(#cols)
- return table.concat(groups(cols, line_qty), "\n")
- end
- function paint_encode.decode(str)
- local outstr = ""
- for pair in str:gsub("\n", ""):gmatch("..") do
- local fst, snd = split_pair(pair)
- outstr = outstr .. string.char(from_nybbles(decode_col(fst), decode_col(snd)))
- end
- return outstr
- end
- function paint_encode.read(file)
- local f = fs.open(file, "r")
- local out = paint_encode.decode(f.readAll())
- f.close()
- return out
- end
- function paint_encode.write(file, str)
- local f = fs.open(file, "w")
- f.write(paint_encode.encode(str))
- f.close()
- end
- return paint_encode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement