2015-05-03 32 views
1

我想用python做二分搜索。像從配置文件Python二進制搜索模式

Address = buff.find(b'\x99\x98\xB1\xFF') 

我想讓這個搜索模式可以通過JSON文件配置。所以,我創建了一個變量,以保持從JSON文件中的數據,如「模式」:「\ X99 \ X98 \ XB1 \ XFF」

 Search_Pattern=Data_Structure[data]["Pattern"] 
     print "Search Pattern:", Search_Pattern 
     Address = buff.find(b'***Search_Pattern***') # this won't work. How to input the function variable here? 

怎麼會喜歡做從ASCII模式,爲淺黃色的二進制格式。找到功能?

回答

-1

使用C++標準模板庫的std :: vector容器,然後使用std :: find。然後你可以編寫一個調用C++的Python模塊。

+1

喜邁克爾,謝謝。我不打給C++。我的程序只是一個純Python代碼。 – user2020514

+1

問題不問關於C++,這是一個python問題 –

+1

你有一個木頭。 –

0

數據類型轉換

json被讀取並解析,該項目可能會被讀作一個字符串,它可以轉換爲一個bytearray並將其直接傳遞給buff.find()作爲參數。

search_pattern_string = json_obj['pattern'] 
search_pattern_bytes = bytearray(search_pattern_string) 
Address = buff.find(search_pattern_bytes) 
+1

thx。一般來說,它有一些修改。 1)刪除JASON文件中十六進制數據的轉義字符2)jason數據將是Unicode。所以需要先將unicode轉換爲字符串。恩。 Search_Pattern_ascii = Search_Pattern.encode('ascii','ignore')3)將數據轉換爲十六進制格式。 Search_Pattern_hex = Search_Pattern_ascii.decode( 「六角」); 4)將十六進制數據輸入到bytearray。恩。 Search_Pattern_Binary.extend(Search_Pattern_hex) – user2020514

+0

沒有看到整個代碼,很難預測這些行之前和之後的確切編碼,變量名稱和一般流程。很高興它的工作雖然!如果有效,你可以接受答案嗎?此外,在評論中很難閱讀代碼,您是否可以編輯您的問題或在代碼塊中添加代碼的答案(如果這對您有用)? – tmthydvnprt

0

更新的解決方案:

JSON文件:

{"Pattern": "9707A5FF"} 

部分Python代碼:

conf_file = open(config_file) 
conf = json.load(conf_file) 
# get the search pattern 
Search_Pattern=conf["Pattern"] 
# convert unicode to ascii 
Search_Pattern_ascii=Search_Pattern.encode('ascii','ignore') 
#convert ascii string to hex data 
Search_Pattern_hex=Search_Pattern_ascii.decode("hex") 
# 
Search_Pattern_Binary = bytearray() 
Search_Pattern_Binary.extend(Search_Pattern_hex) 

infile = open(Bin_file,'rb') 
buff = infile.read() 
Address = buff.find(Search_Pattern_Binary) 

....