我需要通过串行线(RS-232)接收来自Arduino的十六进制编码的单精度大端浮点值。如何将它们转换成Python的float,后者是具有双精度的大endian?在
Arduino发送类似“8192323E”的内容,在Python中我希望有0.174387。我找到了“Convert hex to float”,但似乎所有这些都不适用于单精度浮点。在
从链接页面来看,这看起来很有前途:from ctypes import *
def convert(s):
i = int(s, 16) # convert from hex to a Python int
cp = pointer(c_int(i)) # make this into a c integer
fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer
return fp.contents.value # dereference the pointer, get the float
我的精度还是不行。在
在Java(Processing)中,我可以做到:
^{pr2}$
供您参考,这是在Arduino上运行的实现十六进制编码的C代码。在void serialFloatPrint(float f) {
byte * b = (byte *) &f;
Serial.print("f:");
for(int i=0; i<4; i++) {
byte b1 = (b[i] >> 4) & 0x0f;
byte b2 = (b[i] & 0x0f);
char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;
Serial.print(c1);
Serial.print(c2);
}
}