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?
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With