How to convert hex string starting with 0 to bytes with certain lenght in python

Viewed 63

I want to convert:

'01' -> \x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
'0001' -> \x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

I tried something like this:

int(data,16).to_bytes(16, byteorder='little')

but this is not working when string starting with '00'. Is there some other way ?

1 Answers

You can use bytes.fromhex and bytes.ljust:

>>> bytes.fromhex('01').ljust(16, b'\0')
b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> bytes.fromhex('0001').ljust(16, b'\0')
b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Related