crc
crc

Reputation: 1505

Reading a binary file into an array

I have a file consisting of a series of 32-bit signed integer values (little endian). How can I read this into an array (or similar) data structure?

I tried this:

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

But the memory table does not contain values that match those in the file. Any suggestions would be appreciated.

Upvotes: 2

Views: 2741

Answers (3)

gwell
gwell

Reputation: 2753

This small sample will read in a 32-bit signed integer from a file and print its value.

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

Upvotes: 8

Judge Maygarden
Judge Maygarden

Reputation: 27583

I'd recommend deserializing the data using lpack.

Upvotes: 3

jpjacobs
jpjacobs

Reputation: 9549

You'll need to convert the strings that image:read() provides you with to the number you want.

Upvotes: 0

Related Questions