在lua中解析文件的二进制文件

劳拉

我需要你的帮助。我有一个带有二进制文件。我知道一个数据包以0x7E开头。我想要一个文件的大表,然后将该表拆分为每个表以0x7E开头的表。我现在开始将二进制文件转换为十六进制并进行处理,但是我认为使用二进制文件会更容易,但是我不知道该怎么做。例如,二进制文件的一行:

V001 ....��* \�..E〜..�.�.V001....��* \�..E$ V001。 ...��* \�..E.... V001 ....��* \�..E〜.. $。Mï¿

多数民众赞成在同一行在十六进制:

56 30 30 31 07 00 00 00 EF BF BD EF BF BD 2A 5C EF BF BD 03 01 45 7E 12 02 EF BF BD 00 EF BF BD 1F 56 30 30 31 01 00 00 00 EF BF BD EF BF BD 2A 5C EF BF BD 03 02 45 24 56 30 30 31 04 00 00 00 EF BF BD EF BF BD 2A 5C EF BF BD 03 02 45 13 00 00 00 56 30 30 31 07 00 00 00 00 EF BF BD BD EF BF BD 2A 5C EF BF BD 03 01 45 7E 12 02 24 00 4D EF BF

我想要这样的输出:

table1 = {7E 12 02 EF BF BD 00 EF BF BD 1F 56 30 30 31 01 00 00 00 EF BF BD EF BF BD 2A 5C EF BF BD BD 03 02 45 24 56 30 30 31 04 00 00 00 EF BF BD EF BF BD 2A 5C EF BF BD 03 02 45 13 00 00 00 56 30 30 31 07 00 00 00 00 EF BF BD EF BF BD BD 2A 5C EF BF BD 03 01 45}

table2 = {7E 12 02 24 00 4D EF BF}

我已经可以读入文件,将其转换为十六进制,并在文件中找到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)

谢谢您的帮助!

劳拉

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

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章