【问题标题】:Convert int to a hex string in python在python中将int转换为十六进制字符串
【发布时间】:2021-06-22 10:05:57
【问题描述】:

我正在尝试将字符串中的 int 转换为 hex。当前的solutions 无法按预期工作。

十六进制必须是\x 格式。例如。 255 -> \xff; 65 -> \x41

Accepted Solution from a similar question

chr(1) # '\x01'; This is okay.
chr(65) # 'A'
chr(255) # 'ÿ'

输出与十六进制完全不同,即使它们等于相应的十六进制值。输出必须是 \x 格式的十六进制。

Using hex()

hex(1) # '0x1'
hex(65) # '0x41'
hex(255) # '0xff'

这里没有运气。 x 后跟0 所以它没有用。 hex(1)1 之前没有0。我想拥有那个。更好的是,我选择的填充长度。 cmets 中建议的repr(chr(65)) 也不起作用。

hex() 替换

chr(255).replace('0', "\\") # '\\xff'
hex(255).replace('0x', "\\x") # '\\xff'

不能使用replace(),因为\ 必须被转义或者代码甚至不起作用。由于涉及复制,我真的很想避免需要修改字符串的解决方案。

int.to_bytes

int.to_bytes(1, 1, 'big') # b'\x01'
int.to_bytes(65, 1, 'big') # b'A'; Why is this suddenly 'A'? Why not b'\x41'
int.to_bytes(255, 1, 'big') # b'\xff'

非常感谢 Pythonic 的高性能解决方案。

【问题讨论】:

  • 问题是python自动将\xff序列解释回来。所以你必须把它写成转义然后打印结果(得到一个反斜杠)或者你总是有解释版本
  • 例如查看print('\x41') 的输出。 \x 在这种情况下是一个转义序列,如果没有必要,将被省略。
  • 但是,您可以将字符串编码为字节对象。与 ascii 字符关联的字节值将作为这些字符显示给您(为了便于阅读 - 有时字节对象实际上是编码字符串,这使得更容易识别什么是什么),而其余的仍将在其转义码中.但这也意味着代码将不准确 - 例如"\xff".encode()b'\xc3\xbf'

标签: python type-conversion hex


【解决方案1】:

使用 f-string 怎么样,可以使用它的格式方法转换为十六进制,然后将其附加到 \x

def int_to_hex(char_as_int: int) -> str:
    return rf"{char_as_int} -> \x{char_as_int:02x}"


for i in (65, 46, 78, 97, 145):
    print(int_to_hex(i))

输出

65 -> \x41
46 -> \x2e
78 -> \x4e
97 -> \x61
145 -> \x91

【讨论】:

    【解决方案2】:

    你可以试试这个:

    def convert_to_hex(num) -> str:
        return "\\" + str(hex(num))[1:]
    
    
    print(convert_to_hex(1))
    

    样本输出:

    1 -> \x1
    2 -> \x2
    254->\xfe
    255->\xff
    

    【讨论】:

      猜你喜欢
      • 2010-09-17
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多