9

I have a long string with hexadecimal characters, for example:

string = "AA55CC3301AA55CC330F234567"

I am using

string.to_bytes(4, 'little')

I would like the final string to be as follows:

6745230F33CC55AA0133CC55AA

but I am getting an error

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

What's wrong here?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [Convert a Python int into a big-endian string of bytes](https://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes) – TAbdiukov Nov 20 '19 at 05:13

5 Answers5

9

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
dkuers
  • 140
  • 1
  • 8
1

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')
0

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

import pwntools

x2 = p32(x1)
TAbdiukov
  • 1,185
  • 3
  • 12
  • 25
-2

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)
Shivam Chawla
  • 390
  • 5
  • 17
-4

Maybe you can reverse string one of way would be

string = "AA55CC3301AA55CC330F234567"[::-1]
Gurult
  • 197
  • 3
  • 12
  • 2
    This is outright incorrect. To change endianness, reversing string seems right to us humans, but is incorrect nonetheless. For example, if we have the byte-array or "0x12 0x34 0x56 0x78", changed endianness output will be "0x78 0x56 0x34 0x12", but not "0x87 0x65 0x43 0x21 – TAbdiukov Dec 03 '19 at 13:35
  • Well I can't +1 because this answer doesn't apply to Tim's question properly. But I had a binary string that was little-endian, and a refresher of the [::-1] slicing trick was very helpful for that, so thank you. – rdtsc Jul 27 '22 at 18:22