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

后端 未结 5 2236
误落风尘
误落风尘 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:22

    To convert from decimal to hex, use:

    dec = 255
    print hex(dec)[2:-1]
    

    That will output the hex value for 255. To convert back to decimal, use

    hex = 1F90
    print int(hex, 16)
    

    That would output the decimal value for 1F90.

    You should be able to reverse the bytes using:

    hex = "901F"
    hexbyte1 = hex[0] + hex[1]
    hexbyte2 = hex[2] + hex[3]
    newhex = hexbyte2 + hexbyte1
    print newhex
    

    and this would output 1F90. Hope this helps!

提交回复
热议问题