Skip to content

Instantly share code, notes, and snippets.

@mebens
Created April 23, 2011 09:39
Show Gist options
  • Save mebens/938502 to your computer and use it in GitHub Desktop.
Save mebens/938502 to your computer and use it in GitHub Desktop.
Functions for quick left and right bitwise shifts in Lua.
function lshift(x, by)
return x * 2 ^ by
end
function rshift(x, by)
return math.floor(x / 2 ^ by)
end
@blackknight36
Copy link

blackknight36 commented Feb 9, 2019

There seems to be a bug in the rshift function as defined here. Shifting a value of 0x01 twice should result in a value of 0 while shifting a value of 0x03 twice should result in a value of 1. Lua will return 0 for both of these operations as shown below.

> print(math.floor(0x01/2^2))
0
> print(math.floor(0x03/2^2))
0

Using the math.round function defined at http://lua-users.org/wiki/SimpleRound appears to fix this however.

> print(math.round(0x01/2^2))
0
> print(math.round(0x03/2^2))
1

I haven't tested the results with larger numbers but for simply 8 bit integer operations this appears to be enough.

@Laumesis
Copy link

Laumesis commented Sep 10, 2021

@blackknight36
0x03 is hexadecimal 3 = binary 11
shifting binary 11 to right twice results 0
floor is correct

@blackknight36
Copy link

Thanks. Not sure what I was thinking here.

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