未经签名而无需比较签名(Unsigned to signed without comparison)

要将32位无符号转换为有符号整数,可以使用:

function convert(n) if n >= 2 ^ 31 then return n - 2 ^ 32 end return n end

没有这种比较,是否可以做到这一点?

PS:这是Lua,因此我不能像C中那样“施放”。

To convert 32-bit unsigned to signed integer one could use:

function convert(n) if n >= 2 ^ 31 then return n - 2 ^ 32 end return n end

Is it possible to do it without that comparison?

PS: This is Lua, hence I cannot "cast" as in C.

最满意答案

也许你可以通过位操作来做到这一点。 在Smalltalk中将是:

^self - (2*(self bitAnd: 16r80000000))

显然bita在Lua中不是原生的,但是现在可以使用各种位库,请参阅http://lua-users.org/wiki/BitwiseOperators

一旦找到合适的位和功能,就可以了

return n - bitand(n,MAXINT)*2

Maybe you could do it with bit operations. In Smalltalk that would be:

^self - (2*(self bitAnd: 16r80000000))

Apparently bitops are not native in Lua, but various bit library seem available, see http://lua-users.org/wiki/BitwiseOperators

Once you find appropriate bitand function, that would be something like

return n - bitand(n,MAXINT)*2未经签名而无需比较签名(Unsigned to signed without comparison)

要将32位无符号转换为有符号整数,可以使用:

function convert(n) if n >= 2 ^ 31 then return n - 2 ^ 32 end return n end

没有这种比较,是否可以做到这一点?

PS:这是Lua,因此我不能像C中那样“施放”。

To convert 32-bit unsigned to signed integer one could use:

function convert(n) if n >= 2 ^ 31 then return n - 2 ^ 32 end return n end

Is it possible to do it without that comparison?

PS: This is Lua, hence I cannot "cast" as in C.

最满意答案

也许你可以通过位操作来做到这一点。 在Smalltalk中将是:

^self - (2*(self bitAnd: 16r80000000))

显然bita在Lua中不是原生的,但是现在可以使用各种位库,请参阅http://lua-users.org/wiki/BitwiseOperators

一旦找到合适的位和功能,就可以了

return n - bitand(n,MAXINT)*2

Maybe you could do it with bit operations. In Smalltalk that would be:

^self - (2*(self bitAnd: 16r80000000))

Apparently bitops are not native in Lua, but various bit library seem available, see http://lua-users.org/wiki/BitwiseOperators

Once you find appropriate bitand function, that would be something like

return n - bitand(n,MAXINT)*2