简体   繁体   English

在Swift中将float转换为little endian

[英]Convert float to little endian in Swift

I'm processing data from a socket and successfully converting the data to Int and Floats with: 我正在处理来自套接字的数据,并使用以下命令成功将数据转换为Int和Floats:

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

Everything was working fine until one iPhone 6 Plus seemed to be using Big Endian for the data. 一切运行良好,直到一部iPhone 6 Plus似乎在使用Big Endian进行数据传输。

I was able to convert the Int without much effort with: 我能够轻松地转换Int:

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

Unfortunately, I cannot seem to figure out how to convert the float data. 不幸的是,我似乎无法弄清楚如何转换浮点数据。

A possible solution is to read the data into a 32-bit integer first, convert the endianness, and finally create the floating point number with the same bit pattern: 一种可能的解决方案是先将数据读取为32位整数,转换字节序,最后创建具有相同位模式的浮点数:

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

Example: 例:

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM