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

前端 未结 7 1276
南笙
南笙 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:18

    Here's my updated version to the original solution.

    /// input: array of bytes 
    /// -> get pointer to byte array (UnsafeBufferPointer<[Byte]>)
    /// -> access its base address
    /// -> rebind memory to target type T (UnsafeMutablePointer)
    /// -> extract and return the value of target type
    func binarytotype  (_ value: [Byte], _: T.Type) -> T
    {
        return value.withUnsafeBufferPointer {
            $0.baseAddress!
              .withMemoryRebound(to: T.self, capacity: 1) {
                $0.pointee
            }
        }
    }
    
    /// input type: value of type T
    /// -> get pointer to value of T
    /// -> rebind memory to the target type, which is a byte array
    /// -> create array with a buffer pointer initialized with the     source pointer
    /// -> return the resulted array
    func typetobinary  (_ value: T) -> [Byte]
    {
        var mv : T = value
        let s : Int = MemoryLayout.size
        return withUnsafePointer(to: &mv) {
            $0.withMemoryRebound(to: Byte.self, capacity: s) {
                Array(UnsafeBufferPointer(start: $0, count: s))
            }
        }
    }
    

    PS: Don't forget to replace Byte with UInt8.

提交回复
热议问题