Skip to content
Advertisement

How to convert a string to bytes with hexadecimal representation in Python?

I am a very beginner at Python. I have a string that is “TEST00000001” and its length is 12. I want to convert this string to a byte with a hexadecimal representation like this b’x54x45x53x54x30x30x30x30x3030x30x31′. As you can see, the length of the two objects has not changed.

So far, I am successfully converting my string to bytes. But the length of converted bytes is 24 instead of 12.

Here is what I’ve done so far:

JavaScript

Can someone help me about converting my string to a byte object (in hex representation) without changing its length?

Advertisement

Answer

To convert a string into bytes in Python, use bytes directly on the string. Don’t call ord or hex on the characters:

JavaScript

And the output is indeed the same as b'x54x45x53x54x30x30x30x30x30x30x30x31':

JavaScript

By contrast, if your input is a string of bytes in padded hexadecimal representation, you need to decode that representation (e.g. using binascii):

JavaScript

Or codecs:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement