0

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.

user3270009
  • 93
  • 1
  • 9

2 Answers2

1

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.

metatoaster
  • 17,419
  • 5
  • 55
  • 66
0

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?

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710