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

前端 未结 7 1247
南笙
南笙 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:32

    Solution in swift 3:

    public func toByteArray(_ value: T) -> [Byte] {
      let totalBytes = MemoryLayout.size
      var value = value
      return withUnsafePointer(to: &value) { valuePtr in
        return valuePtr.withMemoryRebound(to: Byte.self, capacity: totalBytes) { reboundPtr in
          return Array(UnsafeBufferPointer(start: reboundPtr, count: totalBytes))
        }
      }
    }
    

提交回复
热议问题