如何在Lua中使用按位运算符XOR?
如何在Lua语言中实现按位运算符?
具体来说,我需要一个异或运算符/方法。
How can I implement bitwise operators in Lua language?
Specifically, I need a XOR operator/method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在Lua 5.2中,您可以使用
bit32
库中的函数。在 Lua 5.3 中,
bit32
库已过时,因为现在有原生 按位运算符。输出:
In Lua 5.2, you can use functions in
bit32
library.In Lua 5.3,
bit32
library is obsoleted because there are now native bitwise operators.Output:
在Lua 5.2中,您可以使用
bit32.bxor
函数。In Lua 5.2, you can use the
bit32.bxor
function.由于您引用了下限函数 3 次,因此对于大多数操作使用过多的循环(小于 2^31 的数字不需要所有 31 个循环),正在使用 ^ 运算符,并且没有利用这一事实a 和 b 可能是具有不同大小的截然不同的数字,你会损失很多效率。该函数也没有本地化,并且您执行的除法运算比您需要的多了两次。我写这篇文章的速度相当快。
一般来说,您会看到大约 3 到 20 倍的改进。
如果您需要的不止于此,请说“与”、“或”和“非”,那么我也可以满足您的要求。
别担心,您不需要改变任何东西。
Since you're referencing the floor function 3 times, using an excessive number of loops for most operations (numbers less than 2^31 don't need all 31 loops), are using the ^ operator, and aren't capitalizing on the fact that a and b might be wildly different numbers with different magnitudes, you're losing a lot of efficiency. The function also isn't localized, and you're doing two more division operations than you need to. I wrote this to be reasonably fast.
In general, you're going to see improvements of about 3 to 20 times.
If you need more than this, say AND, OR, and NOT, then I've got you covered there, too.
Don't worry, you won't need to change anything.
如果您需要一种有效的方法来进行按位移位,我写了 不久前有一篇关于此的文章。以下是封装该技术的一些函数:
If you're needing an efficient way to do bitwise shifts, I wrote an article about that a while ago. Here's some functions which wrap the technique:
来自OP;从问题转移到这个答案。
这就是我在 Lua 中实现 XOR 的方式:
From the OP; moved from question into this answer.
This is how I implemented XOR in Lua:
尝试:
Try:
这很简单。使用NAND逻辑。
https://en.wikipedia.org/wiki/NAND_logic
如果您还需要 1,0输入将以下内容插入到函数中
希望这对某人有帮助。
This is very simple. use NAND logic.
https://en.wikipedia.org/wiki/NAND_logic
if you also need 1,0 inputs insert the following to the function
Hope this helps someone.