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

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

    Print formatting also works with strings.

    # Get the hex digits, without the leading '0x'
    hex_str = '%04X' % (36895)
    
    # Reverse the bytes using string slices.
    # hex_str[2:4] is, oddly, characters 2 to 3.
    # hex_str[0:2] is characters 0 to 1.
    str_to_convert = hex_str[2:4] + hex_str[0:2]
    
    # Read back the number in base 16 (hex)
    reversed = int(str_to_convert, 16)
    
    print(reversed) # 8080!
    

提交回复
热议问题