axmol/cocos/scripting/lua-bindings/script/cocos2d/bitExtend.lua

97 lines
1.6 KiB
Lua
Raw Normal View History

2014-07-14 18:26:39 +08:00
-- bit operation
bit = bit or {}
bit.data32 = {}
2014-10-11 01:27:12 +08:00
2014-07-14 18:26:39 +08:00
for i=1,32 do
bit.data32[i]=2^(32-i)
end
2014-10-11 01:27:12 +08:00
function bit._b2d(arg)
local nr=0
2014-07-14 18:26:39 +08:00
for i=1,32 do
if arg[i] ==1 then
2014-10-11 01:27:12 +08:00
nr=nr+bit.data32[i]
2014-07-14 18:26:39 +08:00
end
end
return nr
end
function bit._d2b(arg)
arg = arg >= 0 and arg or (0xFFFFFFFF + arg + 1)
2014-10-11 01:27:12 +08:00
local tr={}
2014-07-14 18:26:39 +08:00
for i=1,32 do
if arg >= bit.data32[i] then
2014-10-11 01:27:12 +08:00
tr[i]=1
arg=arg-bit.data32[i]
2014-07-14 18:26:39 +08:00
else
2014-10-11 01:27:12 +08:00
tr[i]=0
2014-07-14 18:26:39 +08:00
end
end
return tr
end
function bit._and(a,b)
2014-10-11 01:27:12 +08:00
local op1=bit._d2b(a)
local op2=bit._d2b(b)
local r={}
2014-07-14 18:26:39 +08:00
for i=1,32 do
if op1[i]==1 and op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return bit._b2d(r)
2014-10-11 01:27:12 +08:00
2014-07-14 18:26:39 +08:00
end
function bit._rshift(a,n)
2014-10-11 01:27:12 +08:00
local op1=bit._d2b(a)
2014-07-14 18:26:39 +08:00
n = n <= 32 and n or 32
n = n >= 0 and n or 0
for i=32, n+1, -1 do
op1[i] = op1[i-n]
end
for i=1, n do
op1[i] = 0
end
2014-10-11 01:27:12 +08:00
2014-07-14 18:26:39 +08:00
return bit._b2d(op1)
end
2014-10-11 01:27:12 +08:00
function bit._not(a)
local op1=bit._d2b(a)
local r={}
2014-07-14 18:26:39 +08:00
for i=1,32 do
if op1[i]==1 then
r[i]=0
else
r[i]=1
end
end
2014-10-11 01:27:12 +08:00
return bit._b2d(r)
2014-07-14 18:26:39 +08:00
end
function bit._or(a,b)
2014-10-11 01:27:12 +08:00
local op1=bit._d2b(a)
local op2=bit._d2b(b)
local r={}
2014-07-14 18:26:39 +08:00
for i=1,32 do
if op1[i]==1 or op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
2014-10-11 01:27:12 +08:00
return bit._b2d(r)
2014-07-14 18:26:39 +08:00
end
2014-10-11 01:27:12 +08:00
bit.band = bit.band or bit._and
2014-07-14 18:26:39 +08:00
bit.rshift = bit.rshift or bit._rshift
2014-10-11 01:27:12 +08:00
bit.bnot = bit.bnot or bit._not