0

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)
1
  • So, just to get it right: for instance the second element of your new string would be x, am I right? Commented Nov 13, 2019 at 4:47

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

I need the format of the result string to be in hex, as in "\x63\x61\x74"
It is already. b'cat' indicates a bytes object or bytestring and is identical to b'\x63\x61\x74'. If it's formatting you're after, you can get the hex representation like this: bytes('cat', 'ascii').hex().
@Flengo what, exactly do you want? Do you want a byte string that has the bytes you are representing in hex, or do you want that actual hex representation as a byte string?
Sorry, I should have been more clear with my question. I need the hex representation as a string. So ultimately, I don't need b'cat' but I need '\x63\x61\x74' as a string instead, based on 'cat' or whatever else it might be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.