简体   繁体   中英

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

You can try doing:

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM