Flengo
Flengo

Reputation: 91

Python convert string to null terminated byte string

I'm trying to convert a python string to a null terminated byte string. I don't need this string for use in my python program, but I need to have the string in this format and use this output somewhere else.

But basically, for example, I would like to convert the string "cat" to "\x63\x61\x74" if possible, in some way or another.

I wasn't able to find a suitable solution for this problem so far.


I have one possible solution, but I was wondering if there was a better way to do this. This just places the hex values in a list. Not in the exact format above, but similar outcome.

text = "asjknlkjsndfskjn"
hexlist = []

for i in range(0, len(str)):
    hexlist.append(hex(ord(str[i:i+1])))

print(hexlist)

Upvotes: 0

Views: 5150

Answers (1)

Seb
Seb

Reputation: 4586

Have you tried this?

>>> bytes('cat', 'ascii')
b'cat'

For null termination simply add NUL:

>>> bytes('cat', 'ascii') + b'\x00'
b'cat\x00'

Edit: To store the hex representation in a string you could do something like this:

>>> ''.join(['\\'+hex(b)[1:] for b in bytes('cat', 'ascii')])
'\\x63\\x61\\x74'
>>> print(_)
\x63\x61\x74

Upvotes: 1

Related Questions