2010-11-23 169 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反序列化數據。