Swift: extract float from byte data

后端 未结 3 1375
醉话见心
醉话见心 2021-01-01 03:11

I\'m looking for a robust and elegant way to extract four big-endian bytes from an array as a Float.

I can get a UInt32 with the bits via something like this:

<
3条回答
  •  独厮守ぢ
    2021-01-01 03:52

    The floating point types have a static _fromBitPattern that will return a value. ._BitsType is a type alias to the correctly sized unsigned integer:

    let data: [Byte] = [0x00, 0x00, 0x00, 0x40, 0x86, 0x66, 0x66, 0x00]
    let dataPtr = UnsafePointer(data)
    let byteOffset = 3
    let bits = UnsafePointer(dataPtr + byteOffset)[0].bigEndian
    let f = Float._fromBitPattern(bits)
    

    You don't see that method in auto-completion, but it's a part of the FloatingPointType protocol. There's an instance method that will give you back the bits, called ._toBitPattern().

提交回复
热议问题