byte reverse AB CD to CD AB with python

后端 未结 4 487
迷失自我
迷失自我 2020-12-17 02:01

I have a .bin file, and I want to simply byte reverse the hex data. Say for instance @ 0x10 it reads AD DE DE C0, want it to read DE AD C0 DE.

I know there is a simp

相关标签:
4条回答
  • 2020-12-17 02:20

    In Python 3.4 you can use this:

    >>> data = b'\xAD\xDE\xDE\xC0'
    >>> swap_data = bytearray(data)
    >>> swap_data.reverse()
    

    the result is

    bytearray(b'\xc0\xde\xde\xad')
    
    0 讨论(0)
  • 2020-12-17 02:23

    In Python 2, the binary file gets read as a string, so string slicing should easily handle the swapping of adjacent bytes:

    >>> original = '\xAD\xDE\xDE\xC0'
    >>> ''.join([c for t in zip(original[1::2], original[::2]) for c in t])
    '\xde\xad\xc0\xde'
    

    In Python 3, the binary file gets read as bytes. Only a small modification is need to build another array of bytes:

    >>> original = b'\xAD\xDE\xDE\xC0'
    >>> bytes([c for t in zip(original[1::2], original[::2]) for c in t])
    b'\xde\xad\xc0\xde'
    

    You could also use the < and > endianess format codes in the struct module to achieve the same result:

    >>> struct.pack('<2h', *struct.unpack('>2h', original))
    '\xde\xad\xc0\xde'
    

    Happy byte swapping :-)

    0 讨论(0)
  • 2020-12-17 02:29

    Python has a list operator to reverse the values of a list --> nameOfList[::-1]

    So, I might store the hex values as string and put them into a list then try something like:

    def reverseList(aList):
    rev = aList[::-1]
    outString = ""
    for el in rev:
        outString += el + " "
    return outString
    
    0 讨论(0)
  • 2020-12-17 02:35
    data = b'\xAD\xDE\xDE\xC0'
    reversed_data = data[::-1]
    print(reversed_data)
    # b'\xc0\xde\xde\xad'
    
    0 讨论(0)
提交回复
热议问题