解析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)

谢谢你的帮助!

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

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

这样你就可以使用Lua的模式匹配功能,这样你就不必编写自己的数据包逻辑了。

我为我的问题找到了另一个答案

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)

最新更新