将二进制文件读入数组

时间:2010-11-23 19:05:52

标签: arrays file-io binary lua

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

我试过了:

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

但是内存表不包含与文件中的值匹配的值。任何建议将不胜感激。

3 个答案:

答案 0 :(得分:8)

这个小样本将从文件读取32位有符号整数并打印其值。

    -- convert bytes (little endian) to a 32-bit two's complement integer
    function bytes_to_int(b1, b2, b3, b4)
      if not b4 then error("need four bytes to convert to int",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") -- contains 01:02:03:04
    if f then
        local x = bytes_to_int(f:read(4):byte(1,4))
        print(x) --> 67305985
    end

答案 1 :(得分:3)

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

答案 2 :(得分:0)

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

相关问题