0

I have:

Float(bitPattern: UInt32(bigEndian: data.withUnsafeBytes { $0.pointee } ))

This code is converting data to float but I want reverse of it, means Float to Data. Please guide me how I can convert.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Varun Naharia
  • 5,318
  • 10
  • 50
  • 84

1 Answers1

6

First create a 32-bit integer with the big-endian representation of the floating point number, then create a Data value from the integer (as demonstrated for example in round trip Swift number types to/from Data):

let value = Float(42.13)
var u32be = value.bitPattern.bigEndian
let data = Data(buffer: UnsafeBufferPointer(start: &u32be, count: 1))
print(data as NSData) // <4228851f>

Verify the result by converting it back to a Float:

let v = Float(bitPattern: UInt32(bigEndian: data.withUnsafeBytes { $0.pointee } ))
print(v) // 42.13
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382