Float
to NSData
:
var float1 : Float = 40.0
let data = NSData(bytes: &float1, length: sizeofValue(float1))
print(data) // <00002042>
... and back to Float
:
var float2 : Float = 0
data.getBytes(&float2, length: sizeofValue(float2))
print(float2) // 40.0
(The same would work for other "simple" types like Double
,
Int
, ...)
Update for Swift 3, using the new Data
type:
var float1 : Float = 40.0
let data = Data(buffer: UnsafeBufferPointer(start: &float1, count: 1))
print(data as NSData) // <00002042>
let float2 = data.withUnsafeBytes { $0.pointee } as Float
print(float2) // 40.0
(See also round trip Swift number types to/from Data)
Update for Swift 4 and later:
var float1 : Float = 40.0
let data = Data(buffer: UnsafeBufferPointer(start: &float1, count: 1))
let float2 = data.withUnsafeBytes { $0.load(as: Float.self) }
print(float2) // 40.0
Remark: load(as:)
requires the data to be properly aligned, for Float
that would be on a 4 byte boundary. See e.g. round trip Swift number types to/from Data for other solutions which work for arbitrarily aligned data.