Skip to content

Instantly share code, notes, and snippets.

@CheyiLin
Last active September 19, 2016 04:56
Show Gist options
  • Save CheyiLin/230749b1937da27b3bf2 to your computer and use it in GitHub Desktop.
Save CheyiLin/230749b1937da27b3bf2 to your computer and use it in GitHub Desktop.
--[[
The MIT License (MIT)
Copyright (c) Cheyi Lin <cheyi.lin@gmail.com>
]]
local bit_xor
if jit and jit.version_num > 20000 then
bit_xor = bit.bxor
else
bit_xor = bit32.bxor
end
-- XOR secret
local secret = 0x3e
local function crypt(s)
local s = s:gsub(".", function (c) return string.char(bit_xor(c:byte(), secret)) end)
return s
end
-- module xint
local xint = {}
function xint:new(n)
local o = setmetatable({}, self)
self.__index = self
self.__tostring = self.tostring
self.__metatable = false
o:set(n)
return o
end
function xint:set(n)
self.v = crypt(tostring(n))
end
function xint:get()
return tonumber(crypt(self.v))
end
function xint:tostring()
return crypt(self.v)
end
-- test
local function printf(fmt, ...)
io.write(string.format(fmt, ...))
end
local function dump_hex(s)
printf("[%d] ", #s)
s:gsub(".", function (s) printf("%02x ", s:byte()) end)
printf("\n")
end
-- initial number
local n = 1001
printf("n: %d (%s)\n", n, type(n))
dump_hex(tostring(n))
-- create xint object
local x = xint:new(n)
printf("x: %s (%s)\n", tostring(x), type(x))
dump_hex(x.v)
-- get number from xint object
local xn = x:get()
printf("xn: %d (%s)\n", xn, type(xn))
-- set number to xint object
x:set(xn + 100000)
printf("x: %s (%s)\n", tostring(x), type(x))
dump_hex(x.v)
@CheyiLin
Copy link
Author

Result:

n: 1001 (number)
[4] 31 30 30 31 
x: 1001 (table)
[4] 0f 0e 0e 0f 
xn: 1001 (number)
x: 101001 (table)
[6] 0f 0e 0f 0e 0e 0f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment