Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,70 @@
local function BitWriter() return {
accumulator = 0, -- For current byte.
bitCount = 0, -- Bits set in current byte.
outChars = {},
-- writer:writeBit( bit )
writeBit = function(writer, bit)
writer.bitCount = writer.bitCount + 1
if bit > 0 then
writer.accumulator = writer.accumulator + 2^(8-writer.bitCount)
end
if writer.bitCount == 8 then
writer:_flush()
end
end,
-- writer:writeLsb( value, width )
writeLsb = function(writer, value, width)
for i = 1, width do
writer:writeBit(value%2)
value = math.floor(value/2)
end
end,
-- dataString = writer:getOutput( )
getOutput = function(writer)
writer:_flush()
return table.concat(writer.outChars)
end,
_flush = function(writer)
if writer.bitCount == 0 then return end
table.insert(writer.outChars, string.char(writer.accumulator))
writer.accumulator = 0
writer.bitCount = 0
end,
} end
local function BitReader(data) return {
bitPosition = 0, -- Absolute position in 'data'.
-- bit = reader:readBit( ) -- Returns nil at end-of-data.
readBit = function(reader)
reader.bitPosition = reader.bitPosition + 1
local bytePosition = math.floor((reader.bitPosition-1)/8) + 1
local byte = data:byte(bytePosition)
if not byte then return nil end
local bitIndex = ((reader.bitPosition-1)%8) + 1
return math.floor(byte / 2^(8-bitIndex)) % 2
end,
-- value = reader:readLsb( width ) -- Returns nil at end-of-data.
readLsb = function(reader, width)
local accumulator = 0
for i = 1, width do
local bit = reader:readBit()
if not bit then return nil end
if bit > 0 then
accumulator = accumulator + 2^(i-1)
end
end
return accumulator
end,
} end

View file

@ -0,0 +1,37 @@
-- Test writing.
local writer = BitWriter()
local input = "Beautiful moon!"
for i = 1, #input do
writer:writeLsb(input:byte(i), 7)
end
local data = writer:getOutput() -- May include padding at the end.
-- Test reading.
local reader = BitReader(data)
local chars = {}
for i = 1, #input do -- Assume the amount of characters is the same as when we wrote the data.
chars[i] = string.char(reader:readLsb(7))
end
local output = table.concat(chars)
-- Show results.
local hexToBin = {["0"]="0000",["1"]="0001",["2"]="0010",["3"]="0011",
["4"]="0100",["5"]="0101",["6"]="0110",["7"]="0111",
["8"]="1000",["9"]="1001",["a"]="1010",["b"]="1011",
["c"]="1100",["d"]="1101",["e"]="1110",["f"]="1111"}
local function charToHex(c)
return string.format("%02x", c:byte())
end
local function formatBinary(data)
return (data:gsub(".", charToHex)
:gsub(".", hexToBin)
:gsub("........", "%0 "))
end
print("In: "..input)
print("Out: "..output)
print("Data: "..formatBinary(data))