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)

相关推荐
北顾笙98015 小时前
day24-数据结构力扣
数据结构·算法·leetcode
LG.YDX15 小时前
笔试训练48天:倒置字符串
数据结构
励志的小陈16 小时前
数据结构--队列(C语言实现)
c语言·开发语言·数据结构
历程里程碑16 小时前
二叉树---二叉树的最大深度
大数据·数据结构·算法·elasticsearch·搜索引擎·全文检索·深度优先
自我意识的多元宇宙16 小时前
树与二叉树--树的基本概念
数据结构·算法
沙振宇17 小时前
【Web】使用Vue3+PlayCanvas开发3D游戏(十)让人物动起来
前端·游戏·3d·人物·
夜悊17 小时前
顺序栈和链栈的C/C++语言描述实现模板
数据结构
黑客说18 小时前
深耕AI,终破局:无限流游戏的核心创新之路
人工智能·游戏
m0_7167652318 小时前
数据结构--单链表的插入、删除、查找详解
c语言·开发语言·数据结构·c++·笔记·学习·visual studio
风酥糖18 小时前
Godot游戏练习01-第28节-显示效果与音效
游戏·游戏引擎·godot