Python concatenate bytes to str

Viewed 5036

Is is possible to concatenate bytes to 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
>>> 

It is not possible based on simple code above.

The reason I'm asking this as I've seen a code where bytes has been concatenated to str? Here is the snipet of the code.

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))

You can see the full code here.

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

2 Answers

Either encode the string to bytes to get a result in bytes:

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

Or decode the bytes into a string to get a result as str:

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

The second code snippet shows strings being concatenated. You will need to convert the bytes to a string (as shown in the question Convert bytes to a string). Try this: b.decode("utf-8") + s. It should give you the output you need.

Related