在Swift中将float转换为little endian

时间:2017-12-12 21:54:18

标签: ios swift

我从套接字处理数据并成功将数据转换为Int和Floats:

let float = data.withUnsafeBytes { $0.pointee } as Float

一切正常,直到一台iPhone 6 Plus似乎使用Big Endian获取数据。

我能够毫不费力地转换Int:

let uint32 = UInt32(littleEndian: data.withUnsafeBytes { $0.pointee })
let int = Int(uint32)

不幸的是,我似乎无法弄清楚如何转换浮点数据。

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是先将数据读入32位整数,然后转换 字节序,最后用。创建浮点数 相同的位模式:

let uint32 = UInt32(bigEndian: data.withUnsafeBytes { $0.pointee })
let float = Float(bitPattern: uint32)

示例:

// IEEE-754 big-endian representation of 1.5:
let data = Data(bytes: [0x3f, 0xc0, 0x00, 0x00])
print(data as NSData)

let uint32 = UInt32(bigEndian: data.withUnsafeBytes { $0.pointee })
let float = Float(bitPattern: uint32)

print(float) // 1.5