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)

相关推荐
艾莉丝努力练剑4 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(五)
c语言·开发语言·数据结构·学习·算法
xienda4 小时前
冒泡、选择、插入排序:三大基础排序算法深度解析(C语言实现)
数据结构·算法·排序算法
future14124 小时前
游戏开发日记7.12
数据结构·学习·c#·游戏开发
皮卡蛋炒饭.5 小时前
数据结构——堆
数据结构·算法
JuneXcy5 小时前
第七章应用题
数据结构
大白话讲知识5 小时前
代码随想录算法训练营第三十一天|738.单调递增的数字 968.监控二叉树
数据结构·算法
秋说6 小时前
【PTA数据结构 | C语言版】后缀表达式求值
c语言·数据结构·算法
海海不掉头发6 小时前
【408考研知识点全面讲解计算机学科专业基础综合(408)】——数据结构之排序
数据结构·考研·排序算法
呆瑜nuage7 小时前
类和对象拓展——日期类
数据结构
一只鱼^_10 小时前
牛客周赛 Round 99
java·数据结构·c++·算法·贪心算法·动态规划·近邻算法