【问题标题】:How to convert a string (hex decimal string) to uint64 in Lua?如何在 Lua 中将字符串(十六进制十进制字符串)转换为 uint64?
【发布时间】:2018-08-31 05:54:16
【问题描述】:

我需要将 sip callId(例如 1097074724_100640573@8.8,8.8)字符串转换为 requestId,并且我正在使用 sha1 摘要来获取哈希。由于内部兼容性,我需要将此十六进制转换为 uint64_t:

--
-- Obtain request-id from callId
-- 
--  Returns hash
--
function common_get_request_id( callId )
   local command = "echo -n \"" .. callId .. "\" | openssl sha1 | sed 's/(stdin)= //g'"
   local handle = assert( io.popen( command, "r" ) )
   local output = handle:read( "*all" )
   local outputHash = string.gsub(output, "\n", "") -- strip newline
   handle:close()

   -- How to convert outputHash to uint64?  
end

我不确定 Lua 是否支持 uint64。还有,怎么转换?

【问题讨论】:

  • SHA1 生成 160 位,而不是 64 位。你想要什么转换?

标签: lua sha uint64


【解决方案1】:

您可以从 Lua 接收两个 32 位整数作为两个“双精度”值,然后在 C 端将它们转换为一个“uint64”。

outputHash = '317acf63c685455cfaaf1c3255eeefd6ca3c5571'

local p = 4241942993 -- some prime below 2^32
local c1, c2 = 0, 0

for a, b in outputHash:gmatch"(%x)(%x)" do
   c1 = (c1 * 16 + tonumber(a, 16)) % p
   c2 = (c2 * 16 + tonumber(b, 16)) % p
end

return c1, c2  -- both numbers 0..(2^32-1)

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 2019-07-27
    • 2013-02-07
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2022-07-22
    • 2011-08-25
    相关资源
    最近更新 更多