-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbit.lua
144 lines (124 loc) · 2.57 KB
/
bit.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
--[[
Description:
FileName:bit.lua
This module provides a selection of bitwise operations.
History:
Initial version created by ÕóÓê 2005-11-10.
Notes:
....
]]
--[[{2147483648,1073741824,536870912,268435456,134217728,67108864,33554432,16777216,
8388608,4194304,2097152,1048576,524288,262144,131072,65536,
32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}
]]
bit={data32={}}
for i=1,32 do
bit.data32[i]=2^(32-i)
end
function bit:d2b(arg)
local tr={}
for i=1,32 do
if arg >= self.data32[i] then
tr[i]=1
arg=arg-self.data32[i]
else
tr[i]=0
end
end
return tr
end --bit:d2b
function bit:b2d(arg)
local nr=0
for i=1,32 do
if arg[i] ==1 then
nr=nr+2^(32-i)
end
end
return nr
end --bit:b2d
function bit:_xor(a,b)
local op1=self:d2b(a)
local op2=self:d2b(b)
local r={}
for i=1,32 do
if op1[i]==op2[i] then
r[i]=0
else
r[i]=1
end
end
return self:b2d(r)
end --bit:xor
function bit:_and(a,b)
local op1=self:d2b(a)
local op2=self:d2b(b)
local r={}
for i=1,32 do
if op1[i]==1 and op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return self:b2d(r)
end --bit:_and
function bit:_or(a,b)
local op1=self:d2b(a)
local op2=self:d2b(b)
local r={}
for i=1,32 do
if op1[i]==1 or op2[i]==1 then
r[i]=1
else
r[i]=0
end
end
return self:b2d(r)
end --bit:_or
function bit:_not(a)
local op1=self:d2b(a)
local r={}
for i=1,32 do
if op1[i]==1 then
r[i]=0
else
r[i]=1
end
end
return self:b2d(r)
end --bit:_not
function bit:_rshift(a,n)
local op1=self:d2b(a)
local r=self:d2b(0)
if n < 32 and n > 0 then
for i=1,n do
for i=31,1,-1 do
op1[i+1]=op1[i]
end
op1[1]=0
end
r=op1
end
return self:b2d(r)
end --bit:_rshift
function bit:_lshift(a,n)
local op1=self:d2b(a)
local r=self:d2b(0)
if n < 32 and n > 0 then
for i=1,n do
for i=1,31 do
op1[i]=op1[i+1]
end
op1[32]=0
end
r=op1
end
return self:b2d(r)
end --bit:_lshift
function bit:print(ta)
local sr=""
for i=1,32 do
sr=sr..ta[i]
end
print(sr)
end