Base64 编码 lua

Base64 编码

-- Base64 字符表

local base64_chars = {

'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',

'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',

'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',

'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'

}

-- Base64 编码函数

function base64_encode (data)

local bits = 0

local cur = 1

local result = {}

for i = 1, #data do

local byte = string.byte (data, i)

bits = bits | (byte << (cur * 8))

cur = cur + 1

if cur == 3 then

for j = 18, -1, -6 do

table.insert (result, base64_chars [1 + (bits>> j) & 0x3F])

end

cur = 0

bits = 0

end

end

if cur > 0 then

for j = (cur * 8), 5, -6 do

table.insert (result, base64_chars [1 + (bits>> j) & 0x3F])

end

while #result % 4 ~= 0 do

table.insert (result, '=')

end

end

return table.concat (result)

end

-- 要编码的字符串

local long_string = "这是一个需要编码的长字符串。"

-- 编码字符串

local encoded_string = base64_encode (long_string)

print ("Base64 编码后的字符串:", encoded_string)

相关推荐
小袁顶风作案28 分钟前
leetcode力扣——27.移除元素、26.删除有序数组的重复项、80.删除有序数组中的重复项 II
数据结构·算法·leetcode
曾几何时`1 小时前
滑动窗口(十五)2962. 统计最大元素出现至少 K 次的子数组(越长越合法型)
数据结构·算法
蜂蜜黄油呀土豆1 小时前
Redis 数据结构详解:从底层实现到应用场景
数据结构·redis·跳表·zset
Bdygsl1 小时前
数据结构 —— 队列
数据结构
于樱花森上飞舞1 小时前
【多线程】CAS和哈希表
java·数据结构·java-ee
编程之路,妙趣横生1 小时前
数据结构(十二) 位图 & 布隆过滤器
数据结构
无言(* ̄(エ) ̄)1 小时前
C语言--运算符/函数/结构体/指针
c语言·开发语言·数据结构·数据库·算法·mongodb
im_AMBER1 小时前
Leetcode 91 子序列首尾元素的最大乘积
数据结构·笔记·学习·算法·leetcode
每天回答3个问题2 小时前
Lua数组
ue4·lua·虚幻引擎
CoderCodingNo2 小时前
【CSP】CSP-XL 2025辽宁复赛真题-第三题, 小L打比赛(match)
数据结构·算法