PythonQuestions
PythonQuestions

Reputation: 3

Convert hex string to usably hex

I want to convert a hex string I read from a file "0xbffffe43" to a value written in little endian "\x43\xfe\xff\xbf".

I've tried using struct.pack but it requires a valid integer. Everytime I try to cast hex functions it will convert the 43. I need this for an assignment around memory exploits.

I have access to python 2.7

a = "0xbffffe43"
...
out = "\x43\xfe\xff\xbf"

Is what I want to achieve

Upvotes: 0

Views: 130

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

You have a string in input. You can convert it to an integer using int and a base.

>>> a = "0xbffffe43"
>>> import struct
>>> out = struct.pack("<I",int(a,16))
>>> out
b'C\xfe\xff\xbf'

The b prefix is there because solution was tested with python 3. But it works as python 2 as well.

C is printed like this because python interprets printable characters. But

>>> b'C\xfe\xff\xbf' == b'\x43\xfe\xff\xbf'
True

see:

Upvotes: 1

Magofoco
Magofoco

Reputation: 5446

You can try doing:

my_hex = 0xbffffe43
my_little_endian = my_hex.to_bytes(4, 'little')
print(my_little_endian)

Upvotes: 1

Related Questions