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

后端 未结 5 2196
误落风尘
误落风尘 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:03
    >>> x = 36895
    >>> ((x << 8) | (x >> 8)) & 0xFFFF
    8080
    >>> hex(x)
    '0x901f'
    >>> struct.unpack('<H',struct.pack('>H',x))[0]
    8080
    >>> hex(8080)
    '0x1f90'
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-01 07:10

    Keep in mind that 'hex'(base 16 0-9 and a-f) and 'decimal'(0-9) are just constructs for humans to represent numbers. It's all bits to the machine.

    The python hex(int) function produces a hex 'string' . If you want to convert it back to decimal:

    >>> x = 36895
    >>> s = hex(x)
    >>> s
    '0x901f'
    >>> int(s, 16)  # interpret s as a base-16 number
    
    0 讨论(0)
  • 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!
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题