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)

相关推荐
SuperW1 小时前
数据结构——队列
数据结构
??tobenewyorker2 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
蓝澈11212 小时前
迪杰斯特拉算法之解决单源最短路径问题
java·数据结构
点金石游戏出海4 小时前
每周资讯 | Krafton斥资750亿日元收购日本动画公司ADK;《崩坏:星穹铁道》新版本首日登顶iOS畅销榜
游戏·ios·业界资讯·apple·崩坏星穹铁道
wsdchong之小马过河4 小时前
2025《烈焰之刃》游戏攻略
游戏
呆瑜nuage4 小时前
数据结构——堆
数据结构
蓝澈11214 小时前
弗洛伊德(Floyd)算法-各个顶点之间的最短路径问题
java·数据结构·动态规划
zl_dfq4 小时前
数据结构 之 【堆】(堆的概念及结构、大根堆的实现、向上调整法、向下调整法)(C语言实现)
数据结构
127_127_1274 小时前
2025 FJCPC 复建 VP
数据结构·图论·模拟·ad-hoc·分治·转化
闪电麦坤954 小时前
数据结构:二维数组(2D Arrays)
数据结构·算法