reorder byte order in hex string (python)

后端 未结 4 1018
再見小時候
再見小時候 2021-01-05 05:17

I want to build a small formatter in python giving me back the numeric values embedded in lines of hex strings.

It is a central part of my formatter and should be re

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 06:02

    This should do exactly what unutbu's version does, but might be slightly easier to follow for some...

    from binascii import unhexlify
    from struct import pack, unpack
    orig = unhexlify('b62e000052e366667a66408d')
    swapped = pack('<6h', *unpack('>6h', orig))
    print unpack('

    Basically, unpack 6 shorts big-endian, repack as 6 shorts little-endian.

    Again, same thing that unutbu's code does, and you should use his.

    edit Just realized I get to use my favorite Python idiom for this... Don't do this either:

    orig = 'b62e000052e366667a66408d'
    swap =''.join(sum([(c,d,a,b) for a,b,c,d in zip(*[iter(orig)]*4)], ()))
    # '2eb60000e3526666667a8d40'
    

提交回复
热议问题