简体   繁体   English

Python 将十六进制字符串转换为字节值

[英]Python convert hex string to byte value

I have this string of bytes:我有这个字节串:

output1 = 'fef00a01'

and I am trying to convert it to bytes:我正在尝试将其转换为字节:

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

This does not satisfies the condition:这不满足条件:

output1 == output2 # <--- returns False

How can I make it to return True?我怎样才能让它返回True?

outpu1 is a string of characters representing a hex value. outpu1是表示十六进制值的字符串。 Your comparison will always yield false without some sort of conversion (they're two different objects underneath).如果没有某种转换,您的比较将始终产生false (它们是下面的两个不同对象)。 It's akin to testing '123' == 123 .这类似于测试'123' == 123

Basically, you need to convert that string to bytes before comparing.基本上,您需要在比较之前将该字符串转换为字节。 Use something like binascii to convert the hex string into actual bytes like so:使用binascii之类的东西将十六进制字符串转换为实际字节,如下所示:

import binascii

output1 = binascii.unhexlify('fef00a01')

Apparently, it is simple:显然,这很简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM