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.
- How can I convert Int32 to Int in Swift?
- AnyObject to Array?
- Swift: How to convert String to UInt?
- Comparing in objective C - Implicit conversion of 'int' to 'id' is disallowed with ARC
- Leading zeros for Int in Swift
- NSNumberFormatter numberFromString is adding a small fraction when converting certain numbers
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:
- Duplicate symbol _OBJC_CLASS_$_Facebook
- Share Extension is not working in Chrome
- getting breakpoint retrieving addressbook data
- Jailcoder with SDK 6.0
- textFieldShouldReturn is not called
- Swift: how add offset to memcpy(…)
- scrollview size with Autolayout: frame is 600×480 in compact/Any size class, bigger than iphone5?
- Apple Push Services created instead of Apple Production iOS Push Services
- sqlite3 – iOS – database is locked
- Which tasks are more suitable to NSOperation than GCD?
- Evaluate math expression in string? (NSString)
- Read Text File in Document Folder – Iphone SDK
- Does anyone know how to detect if a user has cancelled an “In App” attempt to install another App version
- How can I do remote debugging in Xcode 4?
- How to set an activity indicator on Custom button in iphone