swift - 在 Swift 中将字节数组转换为 double

标签 swift casting type-conversion

如何在 Swift 中将字节数组转换为 double 值?

(这是一个 NSInputStream 扩展)

我的代码片段附在下面,但它没有返回正确的 double 值:

func readDouble() -> Double
{
var readBuffer = Array<UInt8>(count:sizeof(Double), repeatedValue: 0)

        let numberOfBytesRead = self.read(&readBuffer, maxLength: readBuffer.count)
        let help1 = Int(readBuffer[0] & 0xff) << 56 | Int(readBuffer[1] & 0xff) << 48
        let help2 = Int(readBuffer[2] & 0xff) << 40 | Int(readBuffer[3] & 0xff) << 32
        let help3 = Int(readBuffer[4] & 0xff) << 24 | Int(readBuffer[5] & 0xff) << 16
        let help4 = (Int(readBuffer[6] & 0xff) << 8) | Int(readBuffer[7] & 0xff)
        return Double(help1 | help2 | help3 | help4)
}

最佳答案

很简单:

extension FloatingPoint {

    init?(_ bytes: [UInt8]) {

        guard bytes.count == MemoryLayout<Self>.size else { return nil }

        self = bytes.withUnsafeBytes {

            return $0.load(fromByteOffset: 0, as: Self.self)
        }
    }
}

let array: [UInt8] =  [0, 0, 0, 0, 0, 0, 240, 63]
let num = Double(array) // 1.0

此代码适用于 Swift 中的任何浮点类型。

ma​​cOS 上的 Swift 3.0(Doublelittle-endian 表示)

您可以查找我的字节转换备忘单 here 。 (小/大端数转换)

关于swift - 在 Swift 中将字节数组转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773367/

相关文章:

ios - 检查 Internet 连接可用性?

swift - 带有 associatedtype 的协议(protocol)与 optional 不兼容

c++ - C 样式转换和 C++ static_cast 到指针的引用

c# - 显式类型转换的好处?

ios - UITextView 聚焦,但用户触摸 UICollectionViewCell。隐藏键盘并运行 didSelectItemAtIndexPath

ios - StringByAppendingPathComponent() 和 WriteToFile()

c - C 中从 int 到 char 的类型转换

java - 通过 ObjectInputStream 保存和加载类的 Arraylist

c++ - 如何将 QString 转换为 std::string?

c++ - 构建 "OpenSubdiv"时错误重载具有类似的转换