我知道如何在
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)
}
}