gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
hey, can you please write base64 in PURE LUA 5.1
- Assistant
Hello! How can I assist you today?
- User
hey, can you please write base64 in PURE LUA 5.1
- Assistant
Hello! How can I assist you today?
hey, can you please write base64 in PURE LUA 5.1
Certainly! Below is a simple implementation of Base64 encoding and decoding in pure Lua 5.1.
local b64 = {}
local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
function b64.encode(data)
local output = {}
local padding = #data % 3
-- Add padding to make the input length a multiple of 3
if padding > 0 then
for i = 1, 3 - padding do
data = data .. "\0" -- Add null bytes for padding
end
end
for i = 1, #data, 3 do
local a = data:byte(i)
local b = data:byte(i + 1)
local c = data:byte(i + 2)
local chunk = a * 65536 + (b or 0) * 256 + (c or 0)
local encoded1 = math.floor(chunk / 262144) % 64 + 1
local encoded2 = math.floor(chunk / 4096) % 64 + 1
local encoded3 = math.floor(chunk / 64) % 64 + 1
local encoded4 = chunk % 64 + 1
output[#output + 1] = b64chars:sub(encoded1, encoded1)
output[#output + 1] = b64chars:sub(encoded2, encoded2)
output[#output + 1] = (b and b64chars:sub(encoded3, encoded3)) or '='
output[#output + 1] = (c and b64chars:sub(encoded4, encoded4)) or '='
end
return table.concat(output)
end
function b64.decode(data)
local output = {}
local len = #data
local padding = 0
-- Count padding
if data:sub(len - 1) == '=' then padding = 2 end
if data:sub(len) == '=' then padding = padding - 1 end
-- Remove padding
data = data:gsub('=', '')
for i = 1, #data, 4 do
local encoded1 = b64chars:find(data:sub(i, i), 1, true) - 1
local encoded2 = b64chars:find(data:sub(i + 1, i + 1), 1, true) - 1
local encoded3 = b64chars:find(data:sub(i + 2, i + 2), 1, true) - 1
local encoded4 = b64chars:find(data:sub(i + 3, i + 3), 1, true) - 1
local chunk = (encoded1 * 262144) + (encoded2 * 4096) + (encoded3 * 64) + encoded4
output[#output + 1] = string.char(chunk / 65536 % 256)
if encoded3 > 0 then output[#output + 1] = string.char(chunk / 256 % 256) end
if encoded4 > 0 then output[#output + 1] = string.char(chunk % 256) end
end
-- Remove padding in output
return table.concat(output):sub(1, -padding - 1)
end
-- Example usage
local original_text = "Hello, World!"
local encoded_text = b64.encode(original_text)
local decoded_text = b64.decode(encoded_text)
print("Original:", original_text)
print("Encoded:", encoded_text)
print("Decoded:", decoded_text)
encode function converts input data into Base64 by grouping every three bytes into a 24-bit group and then splitting it into four 6-bit groups.decode function performs the reverse operation - converting Base64 back to the original byte string.You can use this code directly in a Lua 5.1 interpreter. Just copy and paste it, and it should work as intended.
Not yet included in a published release.