Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl unpack to Python Conversion

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?

like image 606
Mastermind Avatar asked Oct 28 '25 07:10

Mastermind


1 Answers

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)
like image 131
falsetru Avatar answered Oct 31 '25 02:10

falsetru