Base64 Encoding and Decoding in Lua

Thanks, I used this to make this other function which stores and loads CFrames from a base64 string compactly:

--Base64 serial encode CFrame
local function SerializeCFrame(cf : CFrame)	
	local function SerializeVector(vec : Vector3)
		return string.pack("f", vec.X) .. string.pack("f", vec.Y) .. string.pack("f", vec.Z)
	end
	
	--Don't need to save Z vector as we can calculate it from the other two
	local allbytes = SerializeVector(cf.XVector) .. SerializeVector(cf.YVector) .. SerializeVector(cf.Position)

	return to_base64(allbytes)
end

local function DeserializeCFrame(cfs : string)
	local bytes = from_base64(cfs)
	
	local function DeserializeVector(bytes)
		local xbytes = bytes:sub(1,4)
		local ybytes = bytes:sub(5,8)
		local zbytes = bytes:sub(9,12)
		
		return Vector3.new(string.unpack("f", xbytes), string.unpack("f", ybytes), string.unpack("f", zbytes))
	end
	
	local x = DeserializeVector(bytes:sub(1,12))
	local y = DeserializeVector(bytes:sub(13,24))
	local z = x:Cross(y)
	local p = DeserializeVector(bytes:sub(25,36))
	
	return CFrame.fromMatrix(p, x, y, z)
end

Example output

Gj08M73Pfy4AAIC/AACAv/D/gjUaPTyzAAAAAAAAAAAAAIC/
<->
CFrame.new(0, 0, -1, 4.38277326e-08, -1, 9.76024239e-07, 5.81647959e-11, 9.76024239e-07, 1, -1, -4.38277326e-08, 5.82075742e-11)

8 Likes