3

I'm struggling myself to replicate the below statement from Perl to Python but I'm not really sure how to perform using the python struct module.

So the code that I need to convert is:

my $hex_string = "DEADBEEF";
my @bytes = map( hex, unpack("(A2)*", $hex_string ) );

The above is equivalent to

my @bytes = ( 0xDE, 0xAD, 0xBE, 0xEF );

A2 doesn't seems to be a good option for Python struct. Can anyone help me with this?

falsetru
  • 357,413
  • 63
  • 732
  • 636
Mastermind
  • 69
  • 2
  • 11
  • `unpack("(A2)*", $s)` splits the string in `$s` into two-character strings. `$s =~ /..?/sg` would be equivalent. – ikegami Apr 12 '16 at 11:30
  • By the way, `map( hex, unpack("(A2)*", $hex_string) )` is better written as `unpack "C*", pack "H*", $hex_string` – ikegami Apr 12 '16 at 12:56
  • Duplicate of [How to create python bytes object from long hex string?](http://stackoverflow.com/questions/443967/how-to-create-python-bytes-object-from-long-hex-string?) – ikegami Apr 12 '16 at 12:59

1 Answers1

3

You can use int with base argument to convert hexadecimal number string to int:

>>> int('15', base=16)
21

>>> val = 15
>>> int(str(val), base=16)
21

UPDATE

To use struct.unpack, first conver the hex_string to binary data using binascii.unhexlify (or binascii.a2b_hex):

>>> import struct, binascii
>>> hex_string = "DEADBEEF"
>>> binascii.unhexlify(hex_string)  # Hexa decimal -> binary data
'\xde\xad\xbe\xef'

>>> struct.unpack('4B', binascii.unhexlify(hex_string))  # 4 = 8 / 2
(222, 173, 190, 239)
>>> struct.unpack('4B', binascii.unhexlify(hex_string)) == (0xDE, 0xAD, 0xBE, 0xEF)
True
>>> struct.unpack('{}B'.format(len(hex_string) // 2), binascii.unhexlify(hex_string))
(222, 173, 190, 239)
falsetru
  • 357,413
  • 63
  • 732
  • 636