【问题标题】:How to return very long integer in Lua如何在 Lua 中返回非常长的整数
【发布时间】:2013-08-08 19:15:56
【问题描述】:

我试图返回很长的整数,但我的结果返回为 “7.6561197971049e+016”。 如何让它返回 76561197971049296 ?

local id64 = 76561197960265728
Z = string.match("STEAM_0:0:5391784", 'STEAM_%d+:%d+:(%d+)')
Y = string.match("STEAM_0:0:5391784", 'STEAM_%d+:(%d+):%d+')
--For 64-bit systems
--Let X, Y and Z constants be defined by the SteamID: STEAM_X:Y:Z.
--Let V be SteamID64 identifier of the account type (0x0110000100000000 in hexadecimal format).
--Using the formula W=Z*2+V+Y
if Z == nil then
    return "none"
else
    return Z*2+id64+Y
end

我现在用这段代码安装了任意精度的 lbc

return  bc.add(bc.number(id64),bc.number(2)):tostring()

它返回 70000000000000002 但如果我从 id64 中删除 3 位数字,它会正确显示。

如何在不删除数字的情况下得到正确的结果?

【问题讨论】:

  • 非常感谢@lhf 提供了使用单个匹配项提取的提示,并展示了如何将字符串作为字符串传递给 bc。成功了!
  • 如果你的长整数适合 64 位,试试我的 lint64,tecgraf.puc-rio.br/~lhf/ftp/lua/#lint64 提供,它比 lbc 更小更简单。
  • 是的,我现在正在使用你的 lint64 库,再次感谢。

标签: parsing lua return steam


【解决方案1】:

您需要对长数字使用字符串。否则,Lua 词法分析器会将它们转换为双精度并在这种情况下失去精度。这是使用我的 lbc 的代码:

local bc=require"bc"
local id64=bc.number"76561197960265728"
local Y,Z=string.match("STEAM_0:0:5391784",'STEAM_%d+:(%d+):(%d+)')
if Z == nil then
    return "none"
else
    return (Z*2+id64+Y):tostring()
end

【讨论】:

    【解决方案2】:

    查看this library 了解任意精度算术。 this so post 你可能也会感兴趣。

    【讨论】:

    • 感谢您将我指向该库,我现在使用此代码有一些不明白的地方:bc.add(id64,2):tostring() 它返回 70000000000000002 为什么会这样? id64 为 76561197960265728。
    • 使用bc.add(id64,bc.number(2)):tostring()
    • 它仍然返回 70000000000000002,我也试过这个。 bc.add(bc.number(id64),bc.number(2)):tostring()
    【解决方案3】:

    假设您的 Lua 实现支持 number 类型中的许多有效数字,您的 return 语句将返回该结果。

    当您将数字转换为字符串或打印它时,您可能会看到指数符号。可以使用string.format函数来控制转换:

    assert( "76561197971049296" == string.format("%0.17g", 76561197971049296))
    

    如果 number 是 IEEE-754 double,则它不起作用。您必须知道 Lua 是如何实现的,并牢记技术限制。

    【讨论】:

    • 谢谢,它不支持,我必须安装 lbc 任意精度库,现在我遇到了我向 collapsar 评论的问题。
    • 太糟糕了 76561197971049296 需要 57 位,而双打只给你 53。
    • 啊,我的答案中的测试在Lua Demo 有效。但是,我应该尝试assert( 76561197971049296 == 76561197971049296 - 1),但没有。
    【解决方案4】:

    如果你安装了luajit,你可以这样做:

    local ffi = require("ffi")
    
    steamid64 = tostring(ffi.new("uint64_t", 76561197960265728) + ffi.new("uint64_t", tonumber(accountid)))
    steamid64 = string.sub(steamid64, 1, -4) -- to remove 'ULL at the end'
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 1970-01-01
      • 2016-12-23
      • 2019-07-21
      • 2021-01-16
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多