Python将字节连接到str

问题描述

是否可以将字节连接到str?

>>> b = b'this is bytes'
>>> s = 'this is string'
>>> b + s
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
TypeError: can't concat str to bytes
>>> 

基于上面的简单代码是不可能的。

之所以问这个原因,是因为我看到了将字节连接到str的代码? 这是代码摘要

buf =  ""
buf += "\xdb\xd1\xd9\x74\x24\xf4\x5a\x2b\xc9\xbd\x0e\x55\xbd"

buffer = "TRUN /.:/" + "A" * 2003 + "\xcd\x73\xa3\x77" + "\x90" * 16 +  buf + "C" * (5060 - 2003 - 4 - 16 - len(buf))

您可以在此处查看完整的代码

http://sh3llc0d3r.com/vulnserver-trun-command-buffer-overflow-exploit/

解决方法

第二个代码段显示了被串联的字符串。您将需要将字节转换为字符串(如问题Convert bytes to a string中所示)。试试这个:b.decode("utf-8") + s。它应该会为您提供所需的输出。

,

将字符串编码为字节,以字节为单位获取结果:

print(b'byte' + 'string'.encode())
# b'bytestring'

或将字节解码为字符串以得到结果为str:

print(b'byte'.decode() + 'string')
# bytestring