问题
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:
Data codification: 0xCCBBAAEE - 0xEE: Exponent, 1 signed byte. - 0xCCBBAA: Mantissa, 3 signed bytes.
My question is: how can I construct an (ios) Float from such Exponent and the Mantissa?
in iOS Float has this initializer: public init(sign: FloatingPointSign, exponent: Int, significand: Float)
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.
回答1:
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
)
This is defined by the BinaryFloatingPoint protocol:
The values passed as
exponentBitPattern
andsignificandBitPattern
are interpreted in the binary interchange format defined by the IEEE 754 specification.
The IEEE 754 mentioned above for (single precision) Float
is:
- Sign bit: 1 bit
- Exponent width: 8 bits
- Significand precision: 24 bits (23 explicitly stored)
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 ;)
来源:https://stackoverflow.com/questions/43517629/how-to-parse-a-float-sent-by-a-bluetooth-device-in-swift