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

编程入门 行业动态 更新时间:2024-10-24 02:36:45
未经签名而无需比较签名(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

更多推荐

本文发布于:2023-08-07 23:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466421.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Unsigned   signed   comparison

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!