Skip to content

Instantly share code, notes, and snippets.

@howmanysmall
Created November 19, 2019 16:16
Show Gist options
  • Select an option

  • Save howmanysmall/a2a5696fef84249a521d697d39c07335 to your computer and use it in GitHub Desktop.

Select an option

Save howmanysmall/a2a5696fef84249a521d697d39c07335 to your computer and use it in GitHub Desktop.
local bit32 = {}
local bit = require("bit")
for Index, Function in next, bit do
bit32[Index] = Function
end
bit32.rrotate = bit.ror
bit32.lrotate = bit.rol
local TwoPower = setmetatable({}, {
__index = function(self, Index)
local Value = 2 ^ Index
self[Index] = Value
return Value
end;
})
local bit32_band = bit.band
local bit32_bnot = bit.bnot
local bit32_rshift = bit.rshift
local bit32_lshift = bit.lshift
--[[**
Returns the unsigned number formed by the bits field to field + width - 1 from n. Bits are numbered from 0 (least significant) to 31 (most significant). All accessed bits must be in the range [0, 31]. The default for width is 1.
@param [t:integer] n The bits.
@param [t:integer] field
@param [t:optional<t:integer>] width The bit width. Defaults to one.
@returns [t:integer]
**--]]
function bit32.extract(n, field, width)
width = width or 1
if field < 0 or field > 31 or width < 0 or field + width > 32 then error("trying to access non-existent bits", 2) end
return bit32_band(bit32_rshift(n, field), TwoPower[width] - 1)
end
--[[**
Returns a copy of n with the bits field to field + width - 1 replaced by the value v. Bits are numbered from 0 (least significant) to 31 (most significant). All accessed bits must be in the range [0, 31]. The default for width is 1.
@param [t:integer] n The bits.
@param [t:integer] v
@param [t:integer] field
@param [t:optional<t:integer>] width The bit width. Defaults to one.
@returns [t:integer]
**--]]
function bit32.replace(n, v, field, width)
width = width or 1
if field < 0 or field > 31 or width < 0 or field + width > 32 then error("trying to access non-existent bits", 2) end
local mask1 = TwoPower[width] - 1
v = bit32_band(v, mask1)
return bit32_band(n, bit32_bnot(bit32_lshift(mask1, field))) + bit32_lshift(v, field)
end
--[[**
Returns a boolean signaling whether the bitwise and of its operands is different from.
@param [t:integer] x
@param [t:integer] y
@returns [t:boolean]
**--]]
function bit32.btest(x, y)
return bit32_band(x, y) ~= 0
end
return bit32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment