在 python 中将定点转换为浮点数时出现问题

Problem converting fixed points to float in python

我正在使用 python numpy 读取 minew 信标,现在我在将固定点转换为浮动时遇到问题。

在 Minew E7 数据表上,我有以下信息: Datasheet infos

我必须将定点数 8.8 转换为浮点数。

我正在使用以下代码进行转换:

from rig.type_casts import fp_to_float

def convertFixedPToFloat(hexaString):
   hexaInt16 = int(hexaString,16)
   f4 = fp_to_float(n_frac=8)
   return (f4(hexaInt16))

如果您查看数据表,十六进制数 0xFFFE 必须为 -0.01,但我的函数返回的是:255.9921875

我的phython版本是Python3.7.3

如何正确转换?

您需要将无符号整数转换为有符号整数。

if hexaInt16 >= 0x8000:
    hexaInt16 -= 0x10000

以上是针对您问题中的数字。对于更通用的无符号到有符号转换,您可以使用此函数。

def signed(n, bits=16):
    n &= (1 << bits) - 1
    if n >> (bits - 1):
        n -= 1 << bits
    return n