如何在swift中将float值转换为byte数组?

时间:2016-04-23 15:17:09

标签: swift floating-point int byte

我用于获取字节数据的代码,但我没有得到正确的浮点值字节数据

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)

2 个答案:

答案 0 :(得分:2)

FloatNSData

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

(另见round trip Swift number types to/from Data。)

答案 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)