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)

相关推荐
白帽黑客cst1 小时前
网络安全(黑客技术) 最新三个月学习计划
网络·数据结构·windows·学习·安全·web安全·网络安全
疑惑的杰瑞1 小时前
[数据结构]算法复杂度详解
c语言·数据结构·算法
大油头儿1 小时前
排序算法-选择排序
数据结构·算法·排序算法
.别止步春天.2 小时前
Python中lambda表达式的使用——完整通透版
数据结构·python·算法
曳渔2 小时前
Java-数据结构-二叉树-习题(三)  ̄へ ̄
java·开发语言·数据结构·算法·链表
shark-chili2 小时前
数据结构与算法-Trie树添加与搜索
java·数据结构·算法·leetcode
Crossoads4 小时前
【数据结构】排序算法---快速排序
c语言·开发语言·数据结构·算法·排序算法
眰恦3744 小时前
数据结构--第五章树与二叉树
数据结构·算法
未 顾4 小时前
JavaSE--集合总览02:单列集合Collection的体系之一:List
数据结构·list
wx200411024 小时前
Codeforces Round 973 (Div. 2) - D题
数据结构·c++·算法