Swift 如何把Int的内存解析为Float的值?

124 阅读1分钟
static func reinterpretToFloat(_ data: Int) -> Double {
    return withUnsafePointer(to: data) {
        return $0.withMemoryRebound(to: Double.self, capacity: 1) {
            return $0.pointee
        }
    }
}
static func reinterpretToInt(_ data: Double) -> Int {
    return withUnsafePointer(to: data) {
        return $0.withMemoryRebound(to: Int.self, capacity: 1) {
            return $0.pointee
        }
    }
}

测试代码

let data = 1.5;
let int = Self.reinterpretToInt(data);
print("\(int)")
let float = Self.reinterpretToFloat(int);
print("\(float)")
let int2  = Self.reinterpretToInt(float);
print("\(int2)")