Python - Decimal to Hex, Reverse byte order, Hex to Decimal

后端 未结 5 2218
误落风尘
误落风尘 2021-01-01 06:51

I\'ve been reading up a lot on stuct.pack and hex and the like.

I am trying to convert a decimal to hexidecimal with 2-bytes. Reverse the hex bit order, then convert

5条回答
  •  春和景丽
    2021-01-01 07:04

    My approach


    import binascii
    
    n = 36895
    reversed_hex = format(n, 'x').decode('hex')[::-1]
    h = binascii.hexlify(reversed_hex)
    print int(h, 16)
    

    or one line

    print int(hex(36895)[2:].decode('hex')[::-1].encode('hex'), 16)
    print int(format(36895, 'x').decode('hex')[::-1].encode('hex'), 16)
    print int(binascii.hexlify(format(36895, 'x').decode('hex')[::-1]), 16)
    

    or with bytearray

    import binascii
    
    n = 36895
    b = bytearray.fromhex(format(n, 'x'))
    b.reverse()
    print int(binascii.hexlify(b), 16)
    

提交回复
热议问题