【问题标题】:Python3 print in hex representationPython3 以十六进制表示形式打印
【发布时间】:2016-04-17 05:33:16
【问题描述】:

我可以找到很多线程告诉我如何将值转换为十六进制。我不想转换任何东西。相反,我想以十六进制表示打印我已经拥有的字节,例如

byteval = '\x60'.encode('ASCII')
print(byteval)  # b'\x60'

当我这样做时,我得到:

byteval = '\x60'.encode('ASCII')
print(byteval)  # b'`' 

因为`是我的字节对应的ASCII字符。

澄清一下:type(byteval) 是字节,而不是字符串。

【问题讨论】:

  • 如果你想让\x60出现,那么你想转换你的字符串。
  • 你可以试试print(hex(ord(byteval)))
  • 我的输入是 Bytes() 类型,而不是字符串,因此我不想转换它。 '\x60' 使用 ASCII 编码是有一个自包含的例子。
  • 我不明白为什么打印 "\x60" 或 "`" 对你很重要?在这两种情况下,执行 ord(byteval) 都会返回 96

标签: python hex


【解决方案1】:
>>> print("b'" + ''.join('\\x{:02x}'.format(x) for x in byteval) + "'")
b'\x60'

【讨论】:

    【解决方案2】:

    看这个:

    hexify = lambda s: [hex(ord(i)) for i in list(str(s))]
    

    和

    print(hexify("abcde"))
    # ['0x61', '0x62', '0x63', '0x64', '0x65']
    

    另一个例子:

    byteval='\x60'.encode('ASCII')
    hexify = lambda s: [hex(ord(i)) for i in list(str(s))]
    print(hexify(byteval))
    # ['0x62', '0x27', '0x60', '0x27']
    

    取自https://helloacm.com/one-line-python-lambda-function-to-hexify-a-string-data-converting-ascii-code-to-hexadecimal/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2015-02-23
      • 2016-08-03
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多