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

How to cast string to uint32 luajit ffi

考虑 str 是一个二进制字符串,它在位置 13 处包含一个 unsigned int 32。

我试过这个:

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

但是,返回的数据是 "cdata" 类型的 unsigned int,我现在不知道如何获取实际值(Int)

索引将 cdata 数组转换为 Lua 数字

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

总的来说,我同意 Egor Skriptunoff 的回答。对于更通用的方法(对于这种特殊情况,可能有点矫枉过正)可以使用联合类型

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

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