简体   繁体   English

十六进制到浮点数的转换

[英]Hex to Float Converstion

Using Windows 10 with Python 3.7.1 and Spyder IDE.使用 Windows 10 与 Python 3.7.1 和 Spyder IDE。

This code segment imports serial and reads from the COM1 port.此代码段导入串行并从 COM1 端口读取。

    ser = serial.Serial('COM1')
    print (ser.name)
    ser.baudrate = 115200
    s = ser.read(100)
    print (s)

I'm expecting to receive a string that looks something like this, straight hex bytes.我期待收到一个看起来像这样的字符串,直接的十六进制字节。

FA 01 08 00 0E A7 C0 C2 68 47 13 BF DD 2F 3E BD 4C B9 FA 01 08 00 DD A6 C0 C2 2D 25 12 BF 21 18 29 BD F3 47 FA 01 08 00 20 A7 C0 C2 55 D1 11 BF E8 B0 3B BD AF 81 FA 01 08 00 0E A7 C0 C2 68 47 13 BF DD 2F 3E BD 4C B9 FA 01 08 00 DD A6 C0 C2 2D 25 12 BF 21 18 29 BD F3 47 FA 01 08 00 20 A7 C0 C2 55 D1 11 BF E8 B0 3B BD AF 81

But I get this displayed from the print(s)但我从印刷品中得到了这个显示

COM1 b'\xfa\x01\x08\x00\xfc\xb0#\xc1\x05\x83\xc1=\x0e\x07\xb2\xbe|\xec\xfa\x01\x08\x00{\x92#\xc10\x14\xca=\xff\xf6\xb6\xbem\x96\xfa\x01\x08\x00G\x9d#\xc1\xd5\xab\xc4=\xa6\x89\xb8\xbe8\xea\xfa\x01\x08\x00\xc2\xba#\xc1\x88\x7f\xca=\x9d\x89\xb5\xbe\xc6\x8c\xfa\x01\x08\x00C\xcd#\xc1\xdc\xa6\xcc=\x8c\x1e\xb6\xbe\x1b\xd4\xfa\x01\x08\x00g\xcb#\xc1\xb5\xbc' COM1 b'\xfa\x01\x08\x00\xfc\xb0#\xc1\x05\x83\xc1=\x0e\x07\xb2\xbe|\xec\xfa\x01\x08\x00{\x92#\xc10 \x14\xca=\xff\xf6\xb6\xbem\x96\xfa\x01\x08\x00G\x9d#\xc1\xd5\xab\xc4=\xa6\x89\xb8\xbe8\xea\xfa\x01\ x08\x00\xc2\xba#\xc1\x88\x7f\xca=\x9d\x89\xb5\xbe\xc6\x8c\xfa\x01\x08\x00C\xcd#\xc1\xdc\xa6\xcc=\ x8c\x1e\xb6\xbe\x1b\xd4\xfa\x01\x08\x00g\xcb#\xc1\xb5\xbc'

Is this just a function of how Python print on a Windows laptop displays hex bytes in a stream read off the COM port? Is this just a function of how Python print on a Windows laptop displays hex bytes in a stream read off the COM port? Is it really just those HEX bytes on the wire?真的只是电线上的那些十六进制字节吗?

Thanks谢谢

What you're seeing is the printout of Python 3's bytes type.您看到的是 Python 3 bytes类型的打印输出。 The \x## chunks are byte hex values that can't be represented in ASCII, while the other characters are bytes that can be represented in ASCII. \x##块是不能用 ASCII 表示的字节十六进制值,而其他字符是可以用 ASCII 表示的字节。

As @ChrisDoyle suggested, you can get the Hex representation withbytes.hex :正如@ChrisDoyle 建议的那样,您可以使用bytes.hex获得十六进制表示:

>>> b = b'\xfa\x01\x08\x00\xfc\xb0#\xc1\x05\x83\xc1=\x0e\x07\xb2\xbe|\xec\xfa\x01\x08\x00{\x92#\xc10\x14\xca=\xff\xf6\xb6\xbem\x96\xfa\x01\x08\x00G\x9d#\xc1\xd5\xab\xc4=\xa6\x89\xb8\xbe8\xea\xfa\x01\x08\x00\xc2\xba#\xc1\x88\x7f\xca=\x9d\x89\xb5\xbe\xc6\x8c\xfa\x01\x08\x00C\xcd#\xc1\xdc\xa6\xcc=\x8c\x1e\xb6\xbe\x1b\xd4\xfa\x01\x08\x00g\xcb#\xc1\xb5\xbc'
>>> b.hex()
'fa010800fcb023c10583c13d0e07b2be7cecfa0108007b9223c13014ca3dfff6b6be6d96fa010800479d23c1d5abc43da689b8be38eafa010800c2ba23c1887fca3d9d89b5bec68cfa01080043cd23c1dca6cc3d8c1eb6be1bd4fa01080067cb23c1b5bc'

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

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