将二进制文件读入数组中。

我有一个包含一系列32位有符号整数值(小端)的文件,如何将其读入数组(或类似的)数据结构中?

我尝试过以下方法:

block = 4
while true do
  local int = image:read(block)
  if not int then break end
  memory[i] = int
  i = i + 1
end

但是,memory表中的值与文件中的值不匹配。如有建议,请指教。

原文链接 https://stackoverflow.com/questions/4259770

点赞
stackoverflow用户513763
stackoverflow用户513763

你需要将 image:read() 提供的字符串转换为你想要的数字。

2010-11-23 20:34:07
stackoverflow用户1491
stackoverflow用户1491

我建议使用lpack来反序列化数据。

2010-11-23 20:43:36
stackoverflow用户173806
stackoverflow用户173806

这个小样例从文件中读入一个32位的有符号整数,并打印它的值。

-- 将 (little endian) 的字节转换为 32 位的补码整数
function bytes_to_int(b1, b2, b3, b4)
  if not b4 then error("需要四个字节才能转换成整数",2) end
  local n = b1 + b2*256 + b3*65536 + b4*16777216
  n = (n > 2147483647) and (n - 4294967296) or n
  return n
end

local f=io.open("test.bin") -- 包含 01:02:03:04
if f then
    local x = bytes_to_int(f:read(4):byte(1,4))
    print(x) --> 67305985
end
2010-11-23 21:09:44