Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 be as follow:

6745230F33CC55AA0133CC55AA

but I am getting an error

AttributeError: 'str' object has no attribute 'to_bytes'

What's wrong here?

like image 971
TimSandiego Hollister Avatar asked Sep 08 '17 06:09

TimSandiego Hollister


2 Answers

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
like image 79
dkuers Avatar answered Nov 09 '22 23:11

dkuers


To convert between little and big-endian you can use this convert_hex function based on int.to_bytes and int.from_bytes:

def int2bytes(i, enc):
    return i.to_bytes((i.bit_length() + 7) // 8, enc)

def convert_hex(str, enc1, enc2):
    return int2bytes(int.from_bytes(bytes.fromhex(str), enc1), enc2).hex()

be = "AA55CC3301AA55CC330F234567"
convert_hex(be, 'big', 'little')
like image 35
Marcus Schiesser Avatar answered Nov 09 '22 23:11

Marcus Schiesser