ios - 在 Swift 中将 float 转换为 little endian

标签 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)

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

最佳答案

一种可能的解决方案是先将数据读入一个 32 位整数,然后将 字节顺序,最后创建 float 相同的位模式:

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

关于ios - 在 Swift 中将 float 转换为 little endian,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47782162/

相关文章:

swift - 如何使用 xcconfig 文件将环境配置添加到具有多个项目的工作区

ios - 如何在 Swift (iOS) 中使用 MKSnapshotter

ios - UIImagePickerControllerDelegate 从 iOS 11 中选取的图像获取日期

ios - 在后台队列上创建和销毁 AVFoundation 类?

ios - 线程 1 : signal SIGABRT;0_abort_with_payload when run on iPhone Swift 4. 1

ios - 如何防止 SKSpriteNode 的子节点与其父节点一起旋转?

ios - CocoaPods Pod 安装奇怪的行为

ios - 从字典数组中获取字典值的范围

iphone - xCode 4.6 - 即使为应用程序启用状态栏也不会出现

ios - 以编程方式添加后 UICollectionView 不滚动