--Lua--十進制轉二進制 function dec_to_binary (data) local dst = "" local remainder, quotient --異常處理 if not data then return dst end --源數據為空 if not tonumber(data) then return dst end --源數據無法轉換為數字 --如果源數據是字符串轉換為數字 if "string" == type(data) then data = tonumber(data) end while true do quotient = math.floor(data / 2) remainder = data % 2 dst = dst..remainder data = quotient if 0 == quotient then break end end --翻轉 dst = string.reverse(dst) --補齊8位 if 8 > #dst then for i = 1, 8 - #dst, 1 do dst = '0'..dst end end return dst end --Lua--二進制轉十進制 function binary_to_dec (data) local dst = 0 local tmp = 0 --異常處理 if not data then return dst end --源數據為空 if not tonumber(data) then return dst end --源數據無法轉換為數字 --如果源數據是字符串去除前面多余的0 if "string" == type(data) then data = tostring(tonumber(data)) end --如果源數據是數字轉換為字符串 if "number" == type(data) then data = tostring(data) end --轉換 for i = #data, 1, -1 do tmp = tonumber(data:sub(-i, -i)) if 0 ~= tmp then for j = 1, i - 1, 1 do tmp = 2 * tmp end end dst = dst + tmp end return dst end --Lua--base64加密 function base64encode(data) local basecode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" local code = "" local dst = "" local tmp local encode_num = 0 --base64編碼后的分組數,6字節為一組 local num = 0 --編碼后后綴"="的個數 local len = 1 --用於統計編碼個數,76個編碼字符換行 --異常處理 if not data then return dst end --源數據為空 --轉換為二進制 for i = 1, #data, 1 do tmp = data:byte(i) if 0 > tmp or 255 < tmp then return dst end code = code..dec_to_binary(tmp) end --字符串長度不能被3整除的情況 num = 3 - #data % 3 if 0 < num then for i = 1, num, 1 do code = code.."00000000" end end encode_num = #code / 6 --開始編碼 for i = 1, #code, 6 do tmp = binary_to_dec(code:sub(i, i + 5)) tmp = tmp + 1 --Lua下標從1開始,切記 if 0 == num then --無"="后綴的情況 dst = dst..basecode:sub(tmp, tmp) len = len + 1 encode_num = encode_num - 1 --每76個字符換行 if 76 == len then dst = dst.."\n" len = 1 end end if 0 < num then --有"="后綴的情況 if encode_num == num and 1 == tmp then dst = dst..'=' len = len + 1 encode_num = encode_num - 1 num = num - 1 --每76個字符換行 if 76 == len then dst = dst.."\n" len = 1 end else dst = dst..basecode:sub(tmp, tmp) len = len + 1 encode_num = encode_num - 1 --每76個字符換行 if 76 == len then dst = dst.."\n" len = 1 end end end end return dst end --Lua--base64解密 function base64decode(data) local basecode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" local dst = "" local code = "" local tmp, index --異常處理 if not data then return dst end --源數據為空 data = data:gsub("\n", "") --去除換行符 data = data:gsub("=", "") --去除'=' for i = 1, #data, 1 do tmp = data:sub(i, i) index = basecode:find(tmp) if nil == index then return dst end index = index - 1 tmp = dec_to_binary(index) code = code..tmp:sub(3) --去除前面多余的兩個'00' end --開始解碼 for i = 1, #code, 8 do tmp = string.char(binary_to_dec(code:sub(i, i + 7))) if nil ~= tmp then dst = dst..tmp end end return dst end
https://www.cnblogs.com/danjing/p/4818462.html