Skip to content

Instantly share code, notes, and snippets.

@annidy
Last active August 16, 2016 12:44
Show Gist options
  • Save annidy/e4d48b613c814de4163f to your computer and use it in GitHub Desktop.
Save annidy/e4d48b613c814de4163f to your computer and use it in GitHub Desktop.
sqlite变长整数
function varint_decode(...)
t = 0
l = 0
for _, i in ipairs{...} do
t = t*128 + bit32.extract(i, 0, 7)
l = l + 1
if bit32.btest(i, 7) == false then
break
end
end
return t, l
end
function varint_encode(t)
i = 0
l = 1
v = {}
repeat
table.insert(v, 1, bit32.extract(t, 0, 7))
t = bit32.rshift(t, 7)
until t == 0
for _, s in pairs(v) do
i = i*256 + s + 0x80
end
i = i - 0x80 -- clear last highest bit
return i, l
end
assert(varint_decode(0x7f) == 0x7f, 1)
assert(varint_decode(0x81, 0x00) == 0x80, 1)
assert(varint_decode(0x81, 0x91, 0xd1, 0xac, 0x78) == 0x12345678, 4)
assert(varint_decode(0x81, 0x81, 0x81, 0x81, 0x01) == 0x10204081, 4)
assert(varint_encode(0x7f) == 0x7f, 1)
assert(varint_encode(0x80) == 0x8100, 2)
assert(varint_encode(0x12345678) == 0x8191d1ac78, 5)
assert(varint_encode(0x10204081) == 0x8181818101, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment