简体   繁体   English

我如何在lua中模拟带符号的32位整数

[英]how do i simulate signed 32bit integer in lua

In Java, when I do following left shift operation, I get a negative result due to integer / long overflow: 0xAAAAAAAA << 7 gives me -183251938048 在Java中,当我执行左移操作时,由于整数/长时间溢出,我得到的结果是负数:0xAAAAAAAA << 7给我-183251938048

But, In Lua since everything is a Lua number which is 52 bit float; 但是,在Lua中,因为一切都是一个52位浮点数的Lua数; I am not able to trigger overflow upon left shift: bit_lshift(0xAAAAAAAA,7) gives me 1431655680 我无法在左移时触发溢出:bit_lshift(0xAAAAAAAA,7)给了我1431655680

How do I simulate 32bit signed integer in Lua?? 如何在Lua中模拟32位有符号整数?

You write some C functions that handle this and then export them to Lua. 您编写一些处理此问题的C函数,然后将它们导出到Lua。

Though generally, Lua code shouldn't be touching things this low-level. 虽然通常来说,Lua代码不应触及这个低层次的东西。

You are looking for bit manipulating libraries in Lua. 您正在寻找Lua中的位操作库。 One such library is bitop from the author of LuaJIT, which directly contains it without the need for installation. bitop的作者是bitop,它是一个这样的库,无需安装即可直接包含它。 You can also install it in standard Lua. 您也可以将其安装在标准Lua中。

Another library is the bit32 library, which is contained in Lua 5.2. 另一个库是bit32库,它包含在Lua 5.2中。

Both libraries let you manipulate 32-bit numbers. 这两个库都允许您操纵32位数字。 For example with bitop : 例如,使用bitop

local bit = require 'bit
print(bit.lshift(0xAAAAAAAA, 7)) --> 1431655680

I do not know how you got the negative number, since 1431655680 is what I get by doing (0xAAAAAAAA<<7)&0xFFFFFFFF in C (and also doing that in a "programming calculator"). 我不知道你怎么得到负数,因为1431655680是我在C语言中执行的操作(0xAAAAAAAA << 7)&0xFFFFFFFF(也是在“编程计算器”中执行的操作)。

I hope I'm not seen as trolling for saying this, but the best way to simulate Java from Lua would be to use Java from Lua. 我希望我不会这么说,但是从Lua模拟Java的最佳方法是使用Lua的Java。

If you need to emulate Java, chances are that your Lua is already embedded in it. 如果您需要模拟Java,则可能是您的Lua已被嵌入其中。 Just expose Java's binary operations to the Lua program, so it can use them. 只需将Java的二进制操作公开给Lua程序,即可使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM