我用于获取字节数据的代码,但我没有得到正确的浮点值字节数据
let count = data.length / sizeof(UInt32)
// create array of appropriate length:
var array = [UInt32](count: count, repeatedValue: 0)
// copy bytes into array
data.getBytes(&array, length:count * sizeof(UInt32))
print(array)
答案 0 :(得分:2)
Float
至NSData
:
var float1 : Float = 40.0
let data = NSData(bytes: &float1, length: sizeofValue(float1))
print(data) // <00002042>
...并返回Float
:
var float2 : Float = 0
data.getBytes(&float2, length: sizeofValue(float2))
print(float2) // 40.0
(同样适用于Double
等其他“简单”类型,
Int
,...)
Data
类型更新Swift 3 :
var float1 : Float = 40.0
let data = Data(buffer: UnsafeBufferPointer(start: &float1, count: 1))
print(data as NSData) // <00002042>
let float2 = data.withUnsafeBytes { $0.pointee } as Float
print(float2) // 40.0
答案 1 :(得分:0)
迅速5 解决方案
从Float
到[UInt8]
extension Float {
var bytes: [UInt8] {
withUnsafeBytes(of: self, Array.init)
}
}
用法:
let number: Float = 36.5
let bytes = number.bytes
从[UInt8]
到Float
bytes.withUnsafeBytes {
$0.load(fromByteOffset: 0, as: Float.self)
}
要转换为数据,只需将字节数组转换为Data
let data = Data(bytes)