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)

相关推荐
摸鱼的春哥3 天前
10年3次大失败,他从“罪人”输成了中年人的“白月光”
游戏
Fanxt_Ja3 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1233 天前
【数据结构】二叉树的概念
数据结构·二叉树
1uther4 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
2501_918126914 天前
用html5写一个flappybird游戏
css·游戏·html5
散1124 天前
01数据结构-01背包问题
数据结构
java搬砖工-苤-初心不变4 天前
基于 lua_shared_dict 的本地内存限流实现
开发语言·junit·lua
消失的旧时光-19434 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww4 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚4 天前
[数据结构] 排序
数据结构