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

前端 未结 7 1279
南笙
南笙 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:25

    typealias Byte = UInt8
    
    func toByteArray(var value: T) -> [Byte] {
        return withUnsafePointer(&value) {
            Array(UnsafeBufferPointer(start: UnsafePointer($0), count: sizeof(T)))
        }
    }
    
    toByteArray(1729.1729)
    toByteArray(1729.1729 as Float)
    toByteArray(1729)
    toByteArray(-1729)
    

    But the results are reversed from your expectations (because of endianness):

    [234, 149, 178, 12, 177, 4, 155, 64]
    [136, 37, 216, 68]
    [193, 6, 0, 0, 0, 0, 0, 0]
    [63, 249, 255, 255, 255, 255, 255, 255]
    

    Added:

    func fromByteArray(value: [Byte], _: T.Type) -> T {
        return value.withUnsafeBufferPointer {
            return UnsafePointer($0.baseAddress).memory
        }
    }
    
    let a: Double = 1729.1729
    let b = toByteArray(a) // -> [234, 149, 178, 12, 177, 4, 155, 64]
    let c = fromByteArray(b, Double.self) // -> 1729.1729
    

    For Xcode8/Swift3.0:

    func toByteArray(_ value: T) -> [UInt8] {
        var value = value
        return withUnsafePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size) {
                Array(UnsafeBufferPointer(start: $0, count: MemoryLayout.size))
            }
        }
    }
    
    func fromByteArray(_ value: [UInt8], _: T.Type) -> T {
        return value.withUnsafeBufferPointer {
            $0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
                $0.pointee
            }
        }
    }
    

    For Xcode8.1/Swift3.0.1

    func toByteArray(_ value: T) -> [UInt8] {
        var value = value
        return withUnsafeBytes(of: &value) { Array($0) }
    }
    
    func fromByteArray(_ value: [UInt8], _: T.Type) -> T {
        return value.withUnsafeBytes {
            $0.baseAddress!.load(as: T.self)
        }
    }
    

提交回复
热议问题