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)

相关推荐
big_rabbit05025 小时前
[算法][力扣101]对称二叉树
数据结构·算法·leetcode
wanhengidc5 小时前
云手机的运行环境如何
运维·服务器·游戏·智能手机·生活
WolfGang0073215 小时前
代码随想录算法训练营 Day11 | 二叉树 part01
数据结构
美好的事情能不能发生在我身上5 小时前
Hot100中的:贪心专题
java·数据结构·算法
剑锋所指,所向披靡!7 小时前
数据结构之线性表
数据结构·算法
m0_672703319 小时前
上机练习第49天
数据结构·算法
样例过了就是过了9 小时前
LeetCode热题100 N 皇后
数据结构·c++·算法·leetcode·dfs·深度优先遍历
Z...........9 小时前
(优选算法)斐波那契数列模型
数据结构·算法
zyjyyds11310 小时前
和为0的四元组-双指针法(C语言实现)
c语言·数据结构·算法
像污秽一样11 小时前
算法设计与分析-习题6.1
数据结构·算法