Varun Naharia
Varun Naharia

Reputation: 5388

How to convert Float to Data with BigEndian?

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.

Upvotes: 0

Views: 873

Answers (1)

Martin R
Martin R

Reputation: 540015

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

Upvotes: 6

Related Questions