ios – 如何将double转换成swift中的字节数组?

前端之家收集整理的这篇文章主要介绍了ios – 如何将double转换成swift中的字节数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道如何在 java中(见 here),但是我找不到java的ByteBuffer,因此它的.putDouble(double value)方法是一个快速的等价物.
基本上,我正在寻找一个这样的功能
func doubleToByteArray(value: Double) -> [UInt8]? {
    . . .
}
doubleToByteArray(1729.1729) // should return [64,155,4,177,12,178,149,234]

解决方法

typealias Byte = UInt8

func toByteArray<T>(var value: T) -> [Byte] {
    return withUnsafePointer(&value) {
        Array(UnsafeBufferPointer(start: UnsafePointer<Byte>($0),count: sizeof(T)))
    }
}

toByteArray(1729.1729)
toByteArray(1729.1729 as Float)
toByteArray(1729)
toByteArray(-1729)

但结果与您的期望相反(因为字节顺序):

[234,64]
[136,37,216,68]
[193,6,0]
[63,249,255,255]

添加

func fromByteArray<T>(value: [Byte],_: T.Type) -> T {
    return value.withUnsafeBufferPointer {
        return UnsafePointer<T>($0.baseAddress).memory
    }
}

let a: Double = 1729.1729
let b = toByteArray(a) // -> [234,64]
let c = fromByteArray(b,Double.self) // -> 1729.1729

对于Xcode8 / Swift3.0:

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

func fromByteArray<T>(_ value: [UInt8],_: T.Type) -> T {
    return value.withUnsafeBufferPointer {
        $0.baseAddress!.withMemoryRebound(to: T.self,capacity: 1) {
            $0.pointee
        }
    }
}

对于Xcode8.1 / Swift3.0.1

func toByteArray<T>(_ value: T) -> [UInt8] {
    var value = value
    return withUnsafeBytes(of: &value) { Array($0) }
}

func fromByteArray<T>(_ value: [UInt8],_: T.Type) -> T {
    return value.withUnsafeBytes {
        $0.baseAddress!.load(as: T.self)
    }
}

猜你在找的iOS相关文章