byte reverse AB CD to CD AB with python

后端 未结 4 492
迷失自我
迷失自我 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: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 :-)

提交回复
热议问题