2010-11-23 168 views
2

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

我尝试这样做:

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

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

回答

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 
+0

谢谢!这工作完美。 – crc 2010-11-23 21:28:31

0

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

3

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