【问题标题】:Python - Decimal to Hex, Reverse byte order, Hex to DecimalPython - 十进制到十六进制,反转字节顺序,十六进制到十进制
【发布时间】:2023-03-14 15:07:01
【问题描述】:

我已经阅读了很多关于 stuct.pack 和 hex 之类的内容。

我正在尝试将十进制转换为 2 字节的十六进制。反转十六进制位顺序,然后将其转换回十进制。

我正在尝试按照这些步骤...在 python 中

Convert the decimal value **36895** to the equivalent 2-byte hexadecimal value:

**0x901F**
Reverse the order of the 2 hexadecimal bytes:

**0x1F90**
Convert the resulting 2-byte hexadecimal value to its decimal equivalent:

**8080**

【问题讨论】:

  • 不存在十六进制和十进制值。它们只是显示价值的方式。 “36895”和“0x901F”是相同的值,以不同的方式显示。
  • struct.unpack('H',x))[0]
  • 看起来你正在改变字节顺序,而不是反转位顺序。反转位顺序就像将 0xAC 更改为 0x35。你正在交换字节。如果您能在错误的 Google 搜索中出现标题时更新标题,我将不胜感激。

标签: python decimal hex bit


【解决方案1】:

移位以交换高/低八位:

>>> x = 36895
>>> ((x << 8) | (x >> 8)) & 0xFFFF
8080

用相反的字节序()打包和解包无符号短(H):

>>> struct.unpack('<H',struct.pack('>H',x))[0]
8080

将 2 字节 little-endian 转换为 big-endian...

>>> int.from_bytes(x.to_bytes(2,'little'),'big')
8080

【讨论】:

    【解决方案2】:

    要将十进制转换为十六进制,请使用:

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

    这将输出 255 的十六进制值。 要转换回十进制,请使用

    hex = 1F90
    print int(hex, 16)
    

    这将输出 1F90 的十进制值。

    您应该能够使用以下方法反转字节:

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

    这将输出 1F90。希望这会有所帮助!

    【讨论】:

    • 如果它是一个较小的数字怎么办,例如hex(10) == '0xa' 这样你的代码就会中断。以一种有条理的方式来做这件事很麻烦。
    • 当然,所以我猜你赢得了学究奖,但我仍然认为这是一种混乱的方式来完成这一点,并且没有表现出对正在发生的数学的理解,这可能就是这个问题的全部内容关于(听起来不像是家​​庭作业吗?)
    • 我同意,这听起来确实像家庭作业,我同意,这是一种混乱的方式,但嘿,就他的目的而言,它是有效的。 :)
    【解决方案3】:

    请记住,“十六进制”(以 16 为基数 0-9 和 a-f)和“十进制”(0-9)只是人类表示数字的构造。这都是机器的一部分。

    python hex(int) 函数产生一个 hex 'string' 。如果要将其转换回十进制:

    >>> x = 36895
    >>> s = hex(x)
    >>> s
    '0x901f'
    >>> int(s, 16)  # interpret s as a base-16 number
    

    【讨论】:

      【解决方案4】:

      打印格式也适用于字符串。

      # 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!
      

      【讨论】:

        【解决方案5】:

        我的方法


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

        或一行

        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)
        

        或使用字节数组

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

        【讨论】:

          最近更新 更多