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)

相关推荐
心仪久了会沦陷17 小时前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
码少女18 小时前
数据结构——图的基础
数据结构
Severus_black20 小时前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
二本咕咕-机械转码1 天前
FreeRTOS深入解析(八)IPC机制之FromISR详解
数据结构·单片机·链表
1-1=01 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
希和20271 天前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
shadowcz0071 天前
屿北:站在新旧时代交接处,赌一场AI原生无限游戏#Infinite Talk
游戏·ai-native
布莱克6051 天前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH2 天前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
zh_xuan2 天前
LeeCode 496. 下一个更大元素I
数据结构·算法·栈·单调栈