Convert String From Big-endian To Little-endian Or Vice Versa In Python
I have a long string with hexadecimal characters. For example: string = 'AA55CC3301AA55CC330F234567' I am using the string.to_bytes(4, 'little') I would like the final string to
Solution 1:
to_bytes
only works with integer, afaik.
You could use bytearray
:
>>>ba = bytearray.fromhex("AA55CC3301AA55CC330F234567")>>>ba.reverse()
To convert it back to string using format
:
>>>s = ''.join(format(x, '02x') for x in ba)>>>print(s.upper())
6745230F33CC55AA0133CC55AA
Solution 2:
Notice your question is very similar to this question from 2009 . While the old thread asks for one-way conversion, and you ask for a "vice-versa" conversion, it is really the same thing, whichever endianness you start with. Let me show,
0x12345678->0x78563412->0x12345678
The conversion is very easy with pwntools
, the tools created for software hacking. In particular, to avoid packing-unpacking mess, pwntools embeds p32() function for exact this purpose
importpwntoolsx2= p32(x1)
Solution 3:
To convert between little and big-endian you can use this convert_hex
function based on int.to_bytes
and int.from_bytes
:
defint2bytes(i, enc):
return i.to_bytes((i.bit_length() + 7) // 8, enc)
defconvert_hex(str, enc1, enc2):
return int2bytes(int.from_bytes(bytes.fromhex(str), enc1), enc2).hex()
be = "AA55CC3301AA55CC330F234567"
convert_hex(be, 'big', 'little')
Solution 4:
Is this the answer/code you are looking for?
def little(string):
t= bytearray.fromhex(string)
t.reverse()
return ''.join(format(x,'02x') for x in t).upper()
little(s=AA55CC3301AA55CC330F234567)
Solution 5:
Maybe you can reverse string one of way would be
string = "AA55CC3301AA55CC330F234567"[::-1]
Post a Comment for "Convert String From Big-endian To Little-endian Or Vice Versa In Python"