【问题标题】:Convert hex number to char string reversed将十六进制数字转换为反转的字符字符串
【发布时间】:2018-11-02 08:35:36
【问题描述】:

我有这个变量

x = 0x61626364

我要字符串"dcba",将十六进制数转换成char,然后反转字符串。

如何在 python 中做到这一点?

【问题讨论】:

  • 你有一个正整数;您使用 hex notation 来生成整数值既不存在也不存在,Python 不会将其存储为十六进制表示法,因此您可以安全地删除 'hex' 前缀。您想将整数转换为字符串。

标签: python string python-3.x python-2.7 hex


【解决方案1】:

使用 int.to_bytes() method 将整数解释为小端顺序的字节:

>>> x = 0x61626364
>>> x.to_bytes(4, 'little')
b'dcba'

你需要知道这个的输出长度。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    x = 0x61626364
    print(x.to_bytes(4, 'little').decode('utf-8'))
    

    解释:

    使用to_bytes(),我们将获取字节码,并使用解码函数获取字符串dcba

    输出:

    dcba
    

    【讨论】:

    • @Simone De Vita:这是你所期待的吗?
    • @SimoneDeVita:请确认答案,以便对其他人有所帮助
    【解决方案3】:
    import math
    
    a = [chr(0xFF&(x>>(8*i))) for i in range(math.ceil(math.log(x, 2)/8))]
    
    b = ""
    
    for i in range(len(a)): b += a[i]
    
    print(b)
    

    【讨论】:

      【解决方案4】:

      享受吧!

      def convert(h):
          result = ''
          while h>0:
              result+=chr(h%256)
              h//=256
          return result
      
      
      >>> convert(0x61626364)
      'dcba'
      >>> convert(0x21646c726f57206f6c6c6548)
      'Hello World!'
      

      【讨论】:

        猜你喜欢
        • 2021-08-01
        • 1970-01-01
        • 2018-01-31
        • 2018-01-26
        • 2013-02-07
        • 2014-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多