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

前端 未结 7 1253
南笙
南笙 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条回答
  •  Happy的楠姐
    2020-11-27 17:16

    The accepted answers are dangerous because of the fact that the MemoryLayout provides you the size of the static type T!

    To workaround the problem you should create a custom protocol and ask for Self in it:

    protocol ByteConvertible {}
    
    extension ByteConvertible {
    
        func toBytes() -> [UInt8] {
    
            let capacity = MemoryLayout.size
            var mutableValue = self
            return withUnsafePointer(to: &mutableValue) {
    
                return $0.withMemoryRebound(to: UInt8.self, capacity: capacity) {
    
                    return Array(UnsafeBufferPointer(start: $0, count: capacity))
                }
            }
        }
    }
    

    I mentioned before that the accepted answers are dangerous and here is an example why:

    let num = UInt8(42)
    MemoryLayout.size(ofValue: num) //=> 1 byte as expected
    let any: Any = num
    MemoryLayout.size(ofValue: any) //=> 32 bytes which is what will happen in the generic functions from the all the answers 
    

    Swift 3.0

提交回复
热议问题