round trip Swift number types to/from Data

后端 未结 3 1419
借酒劲吻你
借酒劲吻你 2020-11-22 04:23

With Swift 3 leaning towards Data instead of [UInt8], I\'m trying to ferret out what the most efficient/idiomatic way to encode/decode swifts vario

3条回答
  •  佛祖请我去吃肉
    2020-11-22 04:56

    In my case, Martin R's answer helped but the result was inverted. So I did a small change in his code:

    extension UInt16 : DataConvertible {
    
        init?(data: Data) {
            guard data.count == MemoryLayout.size else { 
              return nil 
            }
        self = data.withUnsafeBytes { $0.pointee }
        }
    
        var data: Data {
             var value = CFSwapInt16HostToBig(self)//Acho que o padrao do IOS 'e LittleEndian, pois os bytes estavao ao contrario
             return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
        }
    }
    

    The problem is related with LittleEndian and BigEndian.

提交回复
热议问题