lua5.1不支持位操作 自己实现
--数字转二进制 代码如下 其中需要注意的地方是 num = num / 2 并不像C中只得整数部分 所以需要处理一下值 用到了lua中math库的math.modf()函数 函数用法如下所示
print(math.modf(12.34)) ---》 12 0.34
数字转二进制代码
--数字转二进制
function ToSecond(num)
local str = ""
local tmp = num
while (tmp > 0) do
if (tmp % 2 == 1) then
str = str .. "1"
else
str = str .. "0"
end
tmp = math.modf(tmp / 2)
end
str = string.reverse(str)
return str
end
接下来的位运算 按位或 按位与 按位取反 由于各个数字转为二进制后的长度不一定一样长 所以首先需要将要比较的两个数字先转为二进制 并且为他们补齐长度 代码如下
--先补齐两个数字的二进制位数
function makeSameLength(num1, num2)
local str1 = ToSecond(num1)
local str2 = ToSecond(num2)
local len1 = string.len(str1)
local len2 = string.len(str2)
print("len1 = " .. len1)
print("len2 = " .. len2)
local len = 0
local x = 0
if (len1 > len2) then
x = len1 - len2
for i = 1, x do
str2 = "0" .. str2
end
len = len1
print("len = "..len)
elseif (len2 > len1) then
x = len2 - len1
for i = 1, x do
str1 = "0" .. str1
end
len = len2
end
len = len1
return str1, str2, len
end
按位或代码
--按位或
function BitOr(num1, num2)
local str1, str2, len = makeSameLength(num1, num2)
local rtmp = ""
for i = 1, len do
local st1 = tonumber(string.sub(str1, i, i))
local st2 = tonumber(string.sub(str2, i, i))
if(st1 ~= 0) then
rtmp = rtmp .. "1"
elseif (st1 == 0) then
print("00000")
if (st2 == 0) then
rtmp = rtmp .. "0"
end
end
end
rtmp = tostring(rtmp)
return rtmp
end
按位与
--按位与
function BitAnd(num1, num2)
local str1, str2, len = makeSameLength(num1, num2)
local rtmp = ""
for i = 1, len do
local st1 = tonumber(string.sub(str1, i, i))
local st2 = tonumber(string.sub(str2, i, i))
if(st1 == 0) then
rtmp = rtmp .. "0"
else
if (st2 ~= 0) then
rtmp = rtmp .. "1"
else
rtmp = rtmp .. "0"
end
end
end
rtmp = tostring(rtmp)
return rtmp
end
按位异或
--按位异或
function BitYiOr(num1, num2)
local str1, str2, len = makeSameLength(num1, num2)
local rtmp = ""
for i = 1, len do
local st1 = tonumber(string.sub(str1, i, i))
local st2 = tonumber(string.sub(str2, i, i))
if (st1 ~= st2) then
rtmp = rtmp .. "1"
else
rtmp = rtmp .. "0"
end
end
rtmp = tostring(rtmp)
return rtmp
end
按位取反
--取反
function Negate(num)
local str = ToSecond(num)
local len = string.len(str)
local rtmp = ""
for i = 1, len do
local st = tonumber(string.sub(str, i, i))
if (st == 1) then
rtmp = rtmp .. "0"
elseif (st == 0) then
rtmp = rtmp .. "1"
end
end
rtmp = tostring(rtmp)
return rtmp
end