将二进制文件读入数组

crc*_*crc 2 arrays binary file-io 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
Run Code Online (Sandbox Code Playgroud)

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

gwe*_*ell 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