File: slowbit32.lua

package info (click to toggle)
minetest-mod-pycraft 0.22-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,744 kB
  • sloc: python: 79,282; makefile: 10
file content (139 lines) | stat: -rw-r--r-- 2,029 bytes parent folder | download | duplicates (3)
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
-- These are super slow 32-bit operations --

local two31 = 2^31
local two32 = 2^32

local to_binary = function(x)
	local pos = two31
	local a = ""
	if x < 0 then
		x = x + two32
	end
	x = x % two32
	for i=1,32 do
		if x >= pos then
			a = a .. "1"
			x = x - pos
		else
			a = a .. "0"
		end
		pos = pos / 2
	end
	return a
end

local from_binary = function(x)
	local z = tonumber(x,2)
	if z >= two31 then
		return z - two32
	else
		return z
	end
end


local band = function(...)
	local a = {}
	local arg = {...}
	for i = 1,#arg do
		a[i] = to_binary(arg[i])
	end
	local c = ""
	for i = 1,32 do
		local value = true
		for j = 1,#arg do
			if a[j]:sub(i,i) == "0" then
				value = false
				break
			end
		end

		if value then
			c = c .. "1"
		else
			c = c .. "0"
		end
	end
	return from_binary(c)
end

local bor = function(...)
	local a = {}
	local arg = {...}
	for i = 1,#arg do
		a[i] = to_binary(arg[i])
	end
	local c = ""
	for i = 1,32 do
		local value = false
		for j = 1,#arg do
			if a[j]:sub(i,i) == "1" then
				value = true
				break
			end
		end

		if value then
			c = c .. "1"
		else
			c = c .. "0"
		end
	end
	return from_binary(c)
end

local bxor = function(...)
	local a = {}
	local arg = {...}
	for i = 1,#arg do
		a[i] = to_binary(arg[i])
	end
	local c = ""
	for i = 1,32 do
		local value = false
		for j = 1,#arg do
			if a[j]:sub(i,i) == "1" then
				value = not value
			end
		end

		if value then
			c = c .. "1"
		else
			c = c .. "0"
		end
	end
	return from_binary(c)
end


local bnot = function(x)
	local a = to_binary(x)
	local c = ""
	for i = 1,32 do
		if a:sub(i,i) == "0" then
			c = c .. "1"
		else
			c = c .. "0"
		end
	end
	return from_binary(c)
end

local lshift = function(x,n)
	return (x * 2^n) % two32
end

local rshift = function(x,n)
	return math.floor(x / 2^n)
end

local rol = function(x,n)
	local a = to_binary(x)
	for i = 1,n do
		a = a:sub(2,32) .. a:sub(1,1)
	end
	return from_binary(a)
end

return {rol=rol, bxor=bxor, bor=bor, band=band, bnot=bnot, lshift=lshift, rshift=rshift}