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)

相关推荐
Benny_Tang1 分钟前
「雅礼集训 2018 Day7」A 题解
数据结构·c++·算法
Lyyaoo.23 分钟前
【回溯】【中等】全排列
java·数据结构·算法
All for pursuit.42 分钟前
【数组-5】560.和为K的子数组
数据结构·c++·算法·leetcode
星子yu1 小时前
【Java数据结构】二叉树 好像就这样?
java·数据结构
玖玥拾1 小时前
Lua 基础语法(八) Unity Huatuo (HybridCLR)
开发语言·unity·游戏引擎·lua
Beyond_System|系统之外1 小时前
【学编程】Python基础编程题100道(1-20)
java·数据结构·算法
船厂电气自动化ai大模型1 小时前
AI大模型与数学 第75课 基、维度、向量空间坐标
数据结构·线性代数·算法·机器学习·推荐算法
程序员阿鹏13 小时前
为什么MySQL InnoDB选择B+树?
数据结构·数据库·b树·sql·mysql·算法·缓存
x10n913 小时前
Postman 汉化完整指南
测试工具·lua·postman
郝学胜-神的一滴15 小时前
C++11 工程级应用 09:告别无谓拷贝,解锁高性能移动语义
开发语言·数据结构·c++·vscode·软件工程·visual studio