Swift: extract float from byte data

I am looking for a reliable and elegant way to extract four bytes from a byte from an array in the form of a Float.

I can get UInt32 with bits through something like this:

let data: [Byte] = [0x00, 0x00, 0x00, 0x40, 0x86, 0x66, 0x66, 0x00] let dataPtr = UnsafePointer<Byte>(data) let byteOffset = 3 let bits = UnsafePointer<UInt32>(dataPtr + byteOffset)[0].bigEndian 

But I cannot find a good way to convert this to Float in Swift.

For example, in Java:

 float f = Float.intBitsToFloat(bits) 

or in C:

 float f = *(float *)&bits; 

I tried pouring dataPtr into a UnsafePointer float, but then the content issue is the issue.

Any suggestions?

+5
source share
3 answers

Floating-point types have a static _fromBitPattern , which returns a value. <Type>._BitsType is a type alias with a full unsigned integer:

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

You do not see this method in completion, but it is part of the FloatingPointType protocol . There is an instance method that will return you bits called ._toBitPattern() .

+5
source

The equivalent Swift code is

 let flt = unsafeBitCast(bits, Float.self) 

which gives 4.2 your data.

+4
source

Here is the solution for Swift 3:

 Float(bitPattern: bits) 
0
source

Source: https://habr.com/ru/post/1207045/


All Articles