【问题标题】:Problem converting fixed points to float in python在python中将固定点转换为浮点数的问题
【发布时间】:2020-01-17 16:02:41
【问题描述】:

我正在使用 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 版本是 Python 3.7.3

如何正确转换它?

【问题讨论】:

    标签: python numpy hex fixed-point


    【解决方案1】:

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

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

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

    def signed(n, bits=16):
        n &= (1 << bits) - 1
        if n >> (bits - 1):
            n -= 1 << bits
        return n
    
    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多