我如何在Lua中使用位运算符XOR?
2019-9-18 11:4:25
收藏:0
阅读:416
评论:7
如何在 Lua 语言中实现位运算符?
具体而言,我需要一个异或运算符/方法。
原文链接 https://stackoverflow.com/questions/5977654
点赞
stackoverflow用户653033
如果你需要一种有效的位移方式,我之前写过一篇关于这方面的文章。以下是一些使用这种技巧的函数:
function lshift(x, by)
return x * 2 ^ by
end
function rshift(x, by)
return math.floor(x / 2 ^ by)
end
2011-05-17 04:30:06
stackoverflow用户3159048
由于你引用了三次 floor 函数,在大多数操作(小于 2^31 的数字不需要所有 31 个循环)中使用了过多的循环,使用了 ^ 运算符,而且没有利用 a 和 b 可能是差异很大的数字并且没有本地化函数,你会失去很多效率。函数也没有本地化,你进行了两次多余的除法运算。我写了这个函数,以使其相当快速。
一般来说,您将会看到大约3到20倍的改进。
local function BitXOR(a,b)--按位异或
local p,c=1,0
while a>0 and b>0 do
local ra,rb=a%2,b%2
if ra~=rb then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
if a<b then a=b end
while a>0 do
local ra=a%2
if ra>0 then c=c+p end
a,p=(a-ra)/2,p*2
end
return c
end
如果你需要更多的,比如 AND,OR 和 NOT,那么我也在这里帮你覆盖。
local function BitOR(a,b)--按位或
local p,c=1,0
while a+b>0 do
local ra,rb=a%2,b%2
if ra+rb>0 then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
return c
end
local function BitNOT(n)
local p,c=1,0
while n>0 do
local r=n%2
if r<1 then c=c+p end
n,p=(n-r)/2,p*2
end
return c
end
local function BitAND(a,b)--按位与
local p,c=1,0
while a>0 and b>0 do
local ra,rb=a%2,b%2
if ra+rb>1 then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
return c
end
别担心,你不需要改变任何东西。
2014-08-31 17:19:04
stackoverflow用户1009479
在 Lua 5.2 中,你可以使用 bit32
库中的函数。
在 Lua 5.3 中,bit32
库已经废弃了,因为现在有原生的位运算符。
print(3 & 5) -- 按位与
print(3 | 5) -- 按位或
print(3 ~ 5) -- 按位异或
print(7 >> 1) -- 按位右移
print(7 << 1) -- 按位左移
print(~7) -- 按位取反
输出结果:
1
7
6
3
14
-8
2015-01-16 11:25:46
stackoverflow用户5714991
这很简单。使用 NAND 逻辑。https://en.wikipedia.org/wiki/NAND_logic
function xor(a,b)
return not( not( a and not( a and b ) ) and not( b and not( a and b ) ) )
end
如果您还需要 1、0 输入,请将以下内容插入函数中。
a = a==1 or a == true -- to accept nil, 1, 0, true or false
b = b==1 or b == true -- to accept nil, 1, 0, true or false
希望这能帮助某个人。
2017-06-07 16:30:04
stackoverflow用户16587
这是我在Lua中实现XOR的方法:
local floor = math.floor
function bxor (a,b)
local r = 0
for i = 0, 31 do
local x = a / 2 + b / 2
if x ~= floor (x) then
r = r + 2^i
end
a = floor (a / 2)
b = floor (b / 2)
end
return r
end
2019-09-18 11:05:30
stackoverflow用户1395767
尝试:
function xor(a,b)
return (a or b) and not (a and b)
end
2021-06-17 12:54:27
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
在 Lua 5.2 中,你可以使用
bit32.bxor
函数。