Swift: extract float from byte data
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:
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).bigEndian
But I can’t figure out a good way to convert this into a Float in Swift.
For example, in Java:
float f = Float.intBitsToFloat(bits)
or in C:
float f = *(float *)&bits;
I tried casting the dataPtr to a float UnsafePointer, but then the endianness is a problem.
3 Solutions Collect From Internet About “Swift: extract float from byte data”
The floating point types have a static
_fromBitPattern that will return a value.
<Type>._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<Byte>(data) let byteOffset = 3 let bits = UnsafePointer<Float._BitsType>(dataPtr + byteOffset).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
The equivalent Swift code is
let flt = unsafeBitCast(bits, Float.self)
4.2 with your data.
Here’s the solution for Swift 3:
- Apns php error “Failed to connect to APNS: 110 Connection timed out.”
- How to get unique id in iOS device?
- iOS Swift 3 : Convert “yyyy-MM-dd'T'HH:mm:ssZ” format string to date object
- Sharing image and text to Facebook Messenger with UIActivityViewController failing
- What is correct way to notify view controller from AppDelegate?
- How can I read a file in a swift playground
- Empty Pod Headers Folder after `pod install`
- Why is my NSNotification its observer called multiple times?
- What are alternatives to “delegates” for passing data between controllers?
- Xcode 4 build setting variables for scheme scripts
- OpenGL ES Shaders and 64-bit iPhone 5S
- Could not load NIB in bundle: 'NSBundle when using storyboarding
- How to connect the audio to bluetooth when playing using AVPlayer
- Transition from UIView to SKView with crossdissolve animation messes up the scaleMode
- React Native v Xamarin Forms – Choosing Cross Platform App Environment