以下是我正在尝试的方法:
import struct
#binary_data = open("your_binary_file.bin","rb").read()
#your binary data would show up as a big string like this one when you .read()
binary_data = '\x44\x69\x62\x65\x6e\x7a\x6f\x79\x6c\x70\x65\x72\x6f\x78\x69\x64\x20\x31\
x32\x30\x20\x43\x20\x30\x33\x2e\x30\x35\x2e\x31\x39\x39\x34\x20\x31\x34\x3a\x32\
x34\x3a\x33\x30'
def search(text):
#convert the text to binary first
s = ""
for c in text:
s+=struct.pack("b", ord(c))
results = binary_data.find(s)
if results == -1:
print ("no results found")
else:
print ("the string [%s] is found at position %s in the binary data"%(text, results))
search("Dibenzoylperoxid")
search("03.05.1994")
这就是我得到的错误:
Traceback (most recent call last):
File "dec_new.py", line 22, in <module>
search("Dibenzoylperoxid")
File "dec_new.py", line 14, in search
s+=struct.pack("b", ord(c))
TypeError: Can't convert 'bytes' object to str implicitly
请让我知道我能做些什么使它正常工作
我正在使用Python 3.5.0
这将不起作用,因为
s
是一个字符串,struct.pack
返回一个字节,不能添加字符串和字节一种可能的解决方案是将
s
设为字节。。。但是用这种方式将字符串转换成字节似乎需要做很多工作。为什么不直接使用
encode()
而且,“当您使用.read()时,您的二进制数据将显示为一个像这样的大字符串”严格来说不是真的。二进制数据不会显示为大字符串,因为它是字节,而不是字符串。如果要创建类似于
open("your_binary_file.bin","rb").read()
返回的字节文字,请使用字节文字语法binary_data = b'\x44\x69<...etc...>\x33\x30'
相关问题 更多 >
编程相关推荐