Convert hexadecimal to normal string

2019-09-07 03:47发布

I'm using Python 3.3.2 and I want convert a hex to a string.

This is my code:
junk = "\x41" * 50 # A
eip = pack("<L", 0x0015FCC4)
buffer = junk + eip

I've tried use

>>> binascii.unhexlify("4142")
b'AB'

... but I want the output "AB", no "b'AB'". What can I do?

Edit:

buffer = junk + binascii.unhexlify(eip).decode('ascii')

binascii.Error: Non-hexadecimal digit found

The problem is I can't concatenate junk + eip.

Thank you.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-09-07 04:24

That's just a literal representation. Don't worry about the b, as it's not actually part of the string itself.

See What does the 'b' character do in front of a string literal?

查看更多
我想做一个坏孩纸
3楼-- · 2019-09-07 04:31

What that b stands for is to denote that is a bytes class, i.e. a string of bytes. If you want to convert that into a string you want to use the decode method.

>>> type(binascii.unhexlify(b"4142"))
<class 'bytes'>
>>> binascii.unhexlify(b"4142").decode('ascii')
'AB'

This results in a string, which is a string of unicode characters.

Edit:

If you want to work purely with binary data, don't do decode, stick with using the bytes type, so in your edited example:

>>> #- junk = "\x41" * 50 # A
>>> junk = b"\x41" * 50 # A
>>> eip = pack("<L", 0x0015FCC4)
>>> buffer = junk + eip
>>> buffer
b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\xc4\xfc\x15\x00'

Note the b in b"\x41", which denote that as a binary string, i.e. standard string type in python2, or literally a string of bytes rather than a string of unicode characters which are two completely different things.

查看更多
登录 后发表回答