为什么bytes.fromhex()奇怪地处理一些十六进制值? [英] Why does bytes.fromhex() treat some hex values strangely?

查看:4595
本文介绍了为什么bytes.fromhex()奇怪地处理一些十六进制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在python中使用套接字库将两个十六进制数字的字节发送到一个编程为接受它们的硬件。要从用户输入的十六进制数字字符串创建字节,我试图使用这里描述的bytes.fromhex()类方法: https://docs.python.org/dev/library/stdtypes.html#bytes.fromhex



为什么会出现下列情况:

  hexstring =bb 0D 02 55 55 5A ce
data = bytes .fromhex(hexstring)
print(data)

给我:

  b'\xbb\r\x02UUZ\xce'

而不是:

  b'\xbb\x0d\ x02 \x55\x55\x5a\xce'



我该如何获得第二个输出?我使用的是python 3.5。

解决方案

这与 bytes.fromhex()。如果您将预期结果输入到Python中,您将得到相同的结果:

 >>> b'\xbb\x0d\x02\x55\x55\x5a\xce'
b'\xbb\r\x02UUZ\xce'
字节的 repr()表示



对象将始终使用ASCII可打印字符和可能的短单字母转义序列。



因此 \x0d 显示为 \r ,因为这是回车的ASCII代码点。 \x55 是可打印的ASCII字符 U 等。



如果这对您是个问题,您必须将您的字节值再次显式转换为十六进制:

 >>> b'\xbb\r\x02UUZ\xce'.hex()
'bb0d0255555ace'


I'm trying to use the socket library in python to send bytes of two hex digits to a piece of hardware programmed to accept them. To create the bytes from a user inputed string of hex digits, I'm trying to use bytes.fromhex() class method described here: https://docs.python.org/dev/library/stdtypes.html#bytes.fromhex

Why does the following:

hexstring = "bb 0D 02 55 55 5A ce"
data = bytes.fromhex(hexstring)
print(data)

give me:

b'\xbb\r\x02UUZ\xce'

instead of:

b'\xbb\x0d\x02\x55\x55\x5a\xce'

?

And how do I get it to give me the second output? I'm using python 3.5.

解决方案

This has nothing to do with bytes.fromhex(). You'd get the same result if you entered your expected result into Python:

>>> b'\xbb\x0d\x02\x55\x55\x5a\xce'
b'\xbb\r\x02UUZ\xce'

The repr() representation of a bytes object will always use ASCII printable characters and short one-letter escape sequences where possible.

So \x0d is displayed as \r, because that's the ASCII code point for a carriage return. \x55 is the printable ASCII character U, etc.

If this is an issue for you, you'll have to explicitly convert your bytes value to hexadecimal again:

>>> b'\xbb\r\x02UUZ\xce'.hex()
'bb0d0255555ace'

这篇关于为什么bytes.fromhex()奇怪地处理一些十六进制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆