我有一个函数,它接受 16 位无符号整数值并将其转换为 double 值。数据来自温度传感器 ( MCP9808 ),该函数将其转换为摄氏度。
该函数定义如下:
double convert_tempc(uint16_t data) {
double temp = data & 0x0FFF;
temp /= 16.0;
if (data & 0x1000) temp -= 256;
return temp;
}
我的问题是,如何执行这一系列操作的逆操作?
我需要一个函数来查找该传感器产生的 16 位值,从而得出给定的摄氏度温度。
由于 16 位值只能表示有限数量的值,因此我想反函数需要找到可以表示的最接近的 double,然后执行反转换。
有什么简单的方法可以做到这一点吗?
该函数是用 C 编写的,但我将用 Python 实现它。
最佳答案
这是一些验证评论中提出的公式的代码。
def u16_to_float(data):
temp = data & 0x0FFF
temp /= 16.0
if data & 0x1000:
temp -= 256
return temp
def float_to_u16(temp):
return int(temp * 16) & 0x1FFF
# test
for data in range(0x2000):
temp = u16_to_float(data)
u = float_to_u16(temp)
assert u == data, (data, temp, u)
print('Ok')
关于c - 求将 16 位无符号整数转换为 double 的函数的逆函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39951457/