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

前端 未结 7 1155
南笙
南笙 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:33

    The method above works, using Swift 2 but, I discovered a much more simpler and faster method to do this conversion and vice versa:

    func binarytotype <T> (value: [UInt8], _: T.Type) -> T
    {
        return value.withUnsafeBufferPointer
        {
            return UnsafePointer<T>($0.baseAddress).memory
        }
    }
    
    func typetobinary <T> (var value: T) -> [UInt8]
    {
        return withUnsafePointer(&value)
        {
            Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: sizeof(T)))
        }
    }
    
    let a: Double = 0.25
    let b: [UInt8] = typetobinary(a) // -> [0, 0, 0, 0, 0, 0, 208, 63]
    let c = binarytotype(b, Double.self) // -> 0.25
    

    I have tested it with Xcode 7.2 in the playground.

    0 讨论(0)
提交回复
热议问题