2017-07-18 99 views
0

我通过UART从热量表接收数据,但我需要一些帮助来了解如何处理数据。 我有文档,但这对我来说还不够,我不太需要这种计算的经验。浮点数据格式符号+指数

也许某个具有合适技能的人可以向我解释如何使用我从文档中获得的更好的示例来完成这项工作。

One value consists of the following bytes: 

[number of bytes][sign+exponent] (integer) 

(integer) is the register data value. The length of the integer value is 
specified by [number of bytes]. [sign+exponent] is an 8-bit value that 
specifies the sign of the data value and sign and value of the exponent. The 
meaning of the individual bits in the [sign+exponent] byte is shown below: 

Sign Exponent

Examples: 

-123.45 = 04h, C2h, 0h, 0h, 30h, 39h 

87654321*103 = 04h, 03h , 05h, 39h, 7Fh, B1h 

255*103 = 01h, 03h , FFh 

现在与实际数据的一个例子。

enter image description here

这是我从这个文件有信息。

这是我从我热量表接收

10 00 56 25 04 42 00 00 1B E4

所以在我的示例然后04是[字节数]一些数据,42是[符号+指数]和00 00 1B E4是(整数)。 但我不知道如何让计算得到实际值。

任何帮助?

回答

1

根据你的例子,你的数据似乎是big-endian。因此,您可以使用位移和掩码将这些字节分解为所需的字段。

n = b[0] 
SI = (b[1] & 0x80) >> 7 
SE = (b[1] & 0x40) >> 6 
exponent = b[1] & 0x3f 
integer = 0 
for i = 0 to n-1: 
    integer = (integer << 8) + b[2+i] 
+0

我在Arduino草图中使用此代码,并进行了一些修改,以便编译但不应改变结果。 但我有一个问题,当我从我的例子0x42计算SE,然后我得到SE = 1但在Yves Daoust的回复中,然后他得到数字-1。 您对此有何看法? 你能解释一下计算整数的部分吗?当我运行代码的时候,结果是-467992576从字节0x00 0x00 0x1B 0xE4而不是7140(来自另一个回复)。 –

+0

@KristofferIsaksson因为你没有说你需要哪种语言,我无法区分有符号和无符号数字。 'integer'的计算应该作为无符号执行。 –

+0

是的,你是对的,你没有足够的信息来回答我。我声明整数作为unsigned int有更多的东西呢?你对SE的看法如何? –

0

尾数的符号从Sign +指数字节的MSb中通过掩码获得(byte & 80h != 0 => SI = -1)。

指数的符号同样由byte & 40h != 0 => SE = -1获得。指数值为EXP = byte & 3Fh

尾数INT是由另外四个字节组成的二进制数,它可以作为一个整数读取(但要记住印度文)。

最后,计算SI * INT * pow(10, SE * EXP)

在你的榜样,SI = 1SE = -1EXP = 2INT = 7140,因此

1 * 7140 * pow(10, -1 * 2) = +71.4 

这不是在这个答案的范围来解释如何有效地实现这一点。

+0

我要读这篇文章一对夫妇更多的时间之前,我得到这一切,但你可以给我一次解释你如何从四个字节0​​0 00 1B E4 –

+0

@KristofferIsaksson得到整数7140:你读一个来自地址的int变量,使用一个指针。 –

+0

我真的很感激你试图向我解释这一点,我很抱歉,但我仍然没有得到它。我明白你是否很快放弃了我。 –