如何在Swift中解析由蓝牙设备发送的浮动消息? [英] How to parse a float, sent by a Bluetooth device, in Swift?
问题描述
在我的iOS应用上,我需要对蓝牙接收的Float值进行解码,并从其他设备(不是iOS)获取4个字节,因此我需要便携式" 4字节Float格式.目前,发件人正在使用以下格式:
On my iOS app I need to decode a Float value received by bluetooth and taking 4 bytes from a different device ( not iOS) so I need a "portable" 4-byte Float format . For now the sender is using this format:
数据编码:0xCCBBAAEE -0xEE:指数,1个有符号字节. -0xCCBBAA:尾数,3个有符号字节.
Data codification: 0xCCBBAAEE - 0xEE: Exponent, 1 signed byte. - 0xCCBBAA: Mantissa, 3 signed bytes.
我的问题是:如何从指数和尾数中构造一个(ios)浮点数?
My question is: how can I construct an (ios) Float from such Exponent and the Mantissa?
具有以下初始化程序: public init(符号:FloatingPointSign,指数:Int,有效数字:Float)
in iOS Float has this initializer: public init(sign: FloatingPointSign, exponent: Int, significand: Float)
我可以轻松地从带符号的尾数中计算出符号参数,从带符号的指数中计算出Exp参数,但是有效参数采用了Float,但是有效参数是Float,我只收到了3个字节的尾数.
I can easily work out the sign param from the signed Mantissa, the Exp param from the signed Exponent but the significant parameter takes a Float BUT the significand param is a Float and I only receive a 3-bytes mantissa.
推荐答案
Assuming you are following the standard IEEE format, which really looks you are — I have a hard time believing this Bluetooth device of yours would use anything else on the wire — then try this initializer instead (available since Swift 3):
init(
sign: FloatingPointSign,
exponentBitPattern: UInt,
significandBitPattern: UInt32
)
这由 BinaryFloatingPoint
协议定义:
This is defined by the BinaryFloatingPoint
protocol:
以
exponentBitPattern
和significandBitPattern
传递的值以IEEE 754规范定义的二进制交换格式解释.
The values passed as
exponentBitPattern
andsignificandBitPattern
are interpreted in the binary interchange format defined by the IEEE 754 specification.
上面提到的(单精度)Float
的IEEE 754是:
The IEEE 754 mentioned above for (single precision) Float
is:
- 符号位:1位
- 指数宽度:8位
- 有效精度:24位(显式存储23位)
其他 Float
初始化程序也应该可以正常工作:
This other Float
initializer should work fine as well:
init(bitPattern: UInt32)
在这两种情况下,只要注意 大端与小端 问题,您应该会很好;)
In both cases, just watch out for big- vs little-endianness issues and you should be fine ;)
这篇关于如何在Swift中解析由蓝牙设备发送的浮动消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!