Python hexidecimal address packing from string

569 views Asked by At

This works correctly:

packed = struct.pack('<L',0x7c023a4f)

This does not:

address = '0x7c023a4f'
packed = struct.pack('<L',address)

How do i make this work? I tried a lot of methods from the binascii library but i cannot seem to figure it out.

2

There are 2 answers

1
Psidom On BEST ANSWER

You can use literal_eval to evaluate the string as hex number before packing it:

from ast import literal_eval
address = '0x7c023a4f'
packed = struct.pack('<L', literal_eval(address))

packed
# 'O:\x02|'
0
kindall On

Convert it to an integer:

address = '0x7c023a4f'
packed = struct.pack('<L', int(address, 16))