字节和字符串之间的一些转换问题

2024-09-28 23:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我正在尝试的方法:

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


Tags: thetextinreadsearchyourdatastring
1条回答
网友
1楼 · 发布于 2024-09-28 23:27:09
s = ""
for c in text:
    s+=struct.pack("b", ord(c))

这将不起作用,因为s是一个字符串,struct.pack返回一个字节,不能添加字符串和字节

一种可能的解决方案是将s设为字节

s = b""

。。。但是用这种方式将字符串转换成字节似乎需要做很多工作。为什么不直接使用encode()

def search(text):
    #convert the text to binary first
    s = text.encode()
    results = binary_data.find(s)
    #etc

而且,“当您使用.read()时,您的二进制数据将显示为一个像这样的大字符串”严格来说不是真的。二进制数据不会显示为大字符串,因为它是字节,而不是字符串。如果要创建类似于open("your_binary_file.bin","rb").read()返回的字节文字,请使用字节文字语法binary_data = b'\x44\x69<...etc...>\x33\x30'

相关问题 更多 >