Skip to content

Instantly share code, notes, and snippets.

@ExtReMLapin
Last active September 13, 2019 08:43
Show Gist options
  • Save ExtReMLapin/ff80219ab846578ced0fb25a598c27e7 to your computer and use it in GitHub Desktop.
Save ExtReMLapin/ff80219ab846578ced0fb25a598c27e7 to your computer and use it in GitHub Desktop.
--fast
function bit.MSB(value)
value = bit.bor(value, bit.rshift(value, 1))
value = bit.bor(value, bit.rshift(value, 2))
value = bit.bor(value, bit.rshift(value, 4))
value = bit.bor(value, bit.rshift(value, 8))
value = bit.bor(value, bit.rshift(value, 16))
value = value + 1
value = bit.rshift(value, 1)
return value
end
--fast
function bit.LSB(value)
return bit.band(-value, value)
end
--fast
function bit.select2(mask, value)
if mask == 0 then return 0 end
local maskOffset = math.log(bit.LSB(mask), 2)
return bit.rshift(bit.band(mask, value), maskOffset)
end
-- slow
function bit.split(value)
-- pre allocate the table
local bit_table = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
local i = 0
while i < 32 do
if bit.rshift(value, i) % 2 == 1 then
bit_table[32 - i] = 1
end
i = i + 1
end
return bit_table
end
function bit.tostring(value, bytes_separator)
if not bytes_separator then
return table.concat(bit.split(value), sepatator)
else
return string.format("%s %s %s %s", table.concat(bit.split(value), sepatator, 1, 8), table.concat(bit.split(value), sepatator, 9, 16), table.concat(bit.split(value), sepatator, 17, 24), table.concat(bit.split(value), sepatator, 25, 32))
end
end
@ExtReMLapin
Copy link
Author

Update :

print("speedtest")
local time;

local max = 50000000
local i;

i = 0
time = os.clock()
while (i < max) do
	bit.select(i, 5646456456)
	i = i + 1
end

print(1, os.clock()-time)



i = 0
time = os.clock()
while (i < max) do
	bit.select2(i, 5646456456)
	i = i + 1
end

print(2, os.clock() - time)

print("qa test")
print(bit.select(0xf, 255) == bit.select2(0xf, 255)) -- should return 15 | 1111
print(bit.select(0xf, 2550) == bit.select2(0xf, 2550)) -- should return 6 | 0110
print(bit.select(0xf0, 42) == bit.select2(0xf0, 42)) -- should return 2 | 0010
print(bit.select(0xf0, 1337) == bit.select2(0xf0, 1337)) -- should return 3 | 0011

Result :

speedtest
1	0.598
2	0.079
qa test
true
true
true
true
[Finished in 0.7s]

Bitwise update is 7.5 times faster

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