0

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

2 Answers2

1

You can try doing:

my_hex = 0xbffffe43
my_little_endian = my_hex.to_bytes(4, 'little')
print(my_little_endian)
Magofoco
  • 5,098
  • 6
  • 35
  • 77
1

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:

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219