How to convert a double into a byte array in swift?

前端 未结 7 1231
南笙
南笙 2020-11-27 17:02

I know how to do it in java (see here), but I couldn\'t find a swift equivalent for java\'s ByteBuffer, and consequently its .putDouble(double value) method.

Basically,
7条回答
  •  粉色の甜心
    2020-11-27 17:13

    Well, it wasn't easy, but here it is:

    func doubleToByteArray(value: Double) -> [UInt8] {
        let count = sizeof(Double)
        var doubles: [Double] = [value]
        let data = NSData(bytes: doubles, length: count)
        var result = [UInt8](count: count, repeatedValue: 0)
        data.getBytes(&result, length: count)
        return result
    }
    

    Use with caution.

提交回复
热议问题