读取二进制文件到一个数组 [英] Reading a binary file into an array

查看:501
本文介绍了读取二进制文件到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有由一系列32位有符号整数值(小端)的文件。我怎样才能阅读本到一个数组(或类似)数据结构?

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?

我试过这样:

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

但内存表不包含匹配文件中的该值。任何建议将是AP preciated。

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

推荐答案

这个小样本将在从文件中的32位有符号整数阅读和打印它的值。

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

这篇关于读取二进制文件到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆