【问题标题】:Python convert hex string to byte valuePython将十六进制字符串转换为字节值
【发布时间】:2021-08-29 09:28:48
【问题描述】:

我有这个字节串:

output1 = 'fef00a01'

我正在尝试将其转换为字节:

output2 = b'\xfe\xf0\n\x01'

这不满足条件:

output1 == output2 # <--- returns False

如何让它返回 True?

【问题讨论】:

  • output1string 类型,output2bytes 类型。你怎么能指望他们是平等的?另外,您能否详细说明您想要实现的目标。
  • 我正在尝试将 output1 转换为 output2
  • 你可以在 Python 中使用bytes() 函数将string 转换为bytes。 BTW output2 的编码是什么?

标签: python python-3.x binary


【解决方案1】:

outpu1 是表示十六进制值的字符串。您的比较将始终产生false,而无需进行某种转换(它们是下面的两个不同对象)。类似于测试'123' == 123

基本上,您需要在比较之前将该字符串转换为字节。使用 binascii 之类的东西将十六进制字符串转换为实际字节,如下所示:

import binascii

output1 = binascii.unhexlify('fef00a01')

【讨论】:

  • 没有外部包怎么办?
【解决方案2】:

显然,这很简单:

>>> bytes.fromhex(output1) 
b'\xfe\xf0\n\x01'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2023-03-07
    • 2022-06-18
    • 2017-08-23
    • 2019-07-27
    • 2018-01-22
    • 2012-06-05
    • 2017-06-17
    相关资源
    最近更新 更多