我有:
Float(bitPattern: UInt32(bigEndian: data.withUnsafeBytes { $0.pointee } ))
此代码将数据转换为浮动,但我希望将其反转,意味着Float to Data。请指导我如何转换。
答案 0 :(得分:3)
首先使用big-endian表示创建一个32位整数
浮点数,然后从整数中创建一个Data
值
(如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>
通过将结果转换回Float
来验证结果:
let v = Float(bitPattern: UInt32(bigEndian: data.withUnsafeBytes { $0.pointee } ))
print(v) // 42.13