如何将字符串转换为uint32 luajit ffi

假设str是一个二进制字符串,它包含位于位置13的无符号整数32。

我尝试过这样做:

local value = ffi.cast("uint32_t", ffi.new("char[4]", str:sub(13,16)))

但是,返回的数据是一个"cdata"类型的无符号整数,我不知道如何获取实际值(即整数)。

点赞
用户6834680
用户6834680

索引转换 cdata 数组为 Lua 数字

local value = ffi.cast("uint32_t*", ffi.new("const char*", str:sub(13,16)))[0]
2019-07-04 14:30:17
用户4984564
用户4984564

通常我同意Egor Skriptunoffs的答案。对于一个更通用的方法(也许对于这个特定的情况有点过头了),可以使用联合类型。

local ffi = require 'ffi'

local union_type = ffi.typeof [[
  union {
    char bytes[4];
    uint32_t integer;
  }
]]

local union = union_type { bytes = 'abcd' }

print(string.format('0x%x', union.integer))

需要注意的是,在这里你需要担心字节序;你可以通过使用ffi.abi('le')ffi.abi('be')来确认你的系统字节序。如果你的字符串来自其他地方(如通过网络),它的字节序很可能在某个地方有记录。

假设你希望将上面示例中的字符串(abcd)解释为大端序;那么你可以这样做:

local union do
  if ffi.abi('le') then
    union = union_type { bytes = ('abcd'):reverse() }
  else
    union = union_type { bytes = 'abcd' }
  end
end

如果系统是小端字节序,则将字符串反转。否则保持原样。

2019-07-05 07:07:21