在Lua中解析文件的二进制

我需要你的帮助。 我有一个带有二进制数据的文件。我知道一个数据包以0x7E开始。我想将整个文件都放到一个大表格中,然后将表格分成以0x7E开头的小表格。 我已经开始将二进制数据转换为十六进制并使用它来处理,但我认为使用二进制会更容易些,但我不知道如何做到这一点。 例如,二进制文件中的一行如下所示:

我已经能够读取文件,将其转换为十六进制并统计文件中的0x7E数量和文件的长度。但是数量和长度并不是必要的信息。我认为使用字符串是错误的,因为它们的字节长度不同。你能帮助我解析文件吗?我也考虑过使用回调函数,但我不知道如何做到这一点。我是新手。 我现在的代码如下所示:

local function read_file(path) --function read_file
 local file = io.open(path, "rb") -- r read mode and b binary mode
 if not file then return nil end
 local content = file:read "*all" -- *all reads the whole file
 file:close()
 return content
end

function string.tohex(str)
 return (str:gsub('.',function(c)
  return string.format('%02X',string.byte(c))
 end))
end

local fileContent = read_file("H:/wireshark/rstp_dtc_0.dat"); --passes file content to function read_file
inhalt = (fileContent):tohex()

s=inhalt
t={}
for k in s:gmatch"(%x%x)" do
 table.insert(t,tonumber(k,16))
end

function tablelength(T)
 local count = 0
 for _ in pairs (T) do count = count +1 end
 return count
end

length = tablelength(t)
print(length)

counter = 0

local items = t
for _, v in pairs(items) do
 if v == 0x7E then
  counter = counter+1
 end
end

print(counter)

谢谢你的帮助!

点赞
用户2858170
用户2858170

一个解决方法是使用 string.gmatch 从文件内容中提取以 "\x7e" 开头的子字符串。

local packets = {}
for packetstr in data:gmatch("\x7e[^\x7e]+") do
  table.insert(packets, {packetstr:byte(1, #packetstr)})
end

这样你就可以使用 Lua 的模式匹配功能来避免编写自己的包逻辑。

2021-02-16 21:12:15
用户15175264
用户15175264

我找到了另一个关于我问题的答案。

function print_table(tab)
 print("Table:")
  for key, value in pairs(tab) do
      io.write(string.format("%02X ", value))
  end
 print("\n")
end

local function read_file(path, callback)
 local file = io.open(path, "rb")
  if not file then
     return nil
  end
 local t = {}
 repeat
    local str = file:read(4 * 1024)
    for c in (str or ''):gmatch('.') do
        if c:byte() == 0x7E then
            callback(t) -- function print_table
            t = {}
        else
            table.insert(t, c:byte())
        end
    end
 until not str
 file:close()
 return t
 end

local result = {}
function add_to_table_of_tables(t)
 table.insert(result, t)
end

local fileContent = read_file("file.dat", print_table)
2021-02-23 08:59:13