如何在 Swift 中解析由蓝牙设备发送的浮点数?

How to parse a float, sent by a Bluetooth device, in Swift?

在我的 iOS 应用程序上,我需要解码蓝牙接收的 Float 值并从不同的设备(不是 iOS)获取 4 个字节,所以我需要一个 "portable" 4-字节浮点格式。目前发件人使用的是这种格式:

数据编码:0xCCBBAAEE - 0xEE:指数,1 个有符号字节。 - 0xCCBBAA:尾数,3 个有符号字节。

我的问题是:如何从这样的指数和尾数构造一个 (ios) 浮点数?

in iOS Float 有这个初始化器: public 初始化(符号:FloatingPointSign,指数:Int,尾数:Float)

我可以很容易地从带符号的尾数中计算出符号参数,从带符号的指数中计算出 Exp 参数,但重要参数采用浮点数,但有效参数是浮点数,我只收到一个 3 字节的尾数。

假设您正在遵循 standard IEEE format,看起来确实如此 — 我很难相信您的这个蓝牙设备会使用线路上的任何其他东西 — 然后试试这个初始化程序(自 Swift3):

init(
    sign: FloatingPointSign, 
    exponentBitPattern: UInt,
    significandBitPattern: UInt32
)

这是由 BinaryFloatingPoint 协议定义的:

The values passed as exponentBitPattern and significandBitPattern are interpreted in the binary interchange format defined by the IEEE 754 specification.

上面提到的(单精度)Float的IEEE 754是:

  • 符号位:1位
  • 指数宽度:8位
  • 有效位数精度:24 位(明确存储 23 位)

另一个 Float initializer 应该也能正常工作:

init(bitPattern: UInt32)

在这两种情况下,只要注意 big- vs little-endianness 问题,您应该没问题;)