一尘不染

如何快速将字节转换为浮点值?

swift

这是我的代码,用于将字节数据转换为浮点数。我尝试了本网站给出的所有答案。我正在获取此“ <44fa0000>”字节数据的指数值

    static func returnFloatValue(mutableData:NSMutableData)->Float
    {
       let qtyRange = mutableData.subdataWithRange(NSMakeRange(0, 4))
       let qtyString = String(qtyRange)
       let qtyTrimString = qtyString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
       let qtyValue =  Float(strtoul(qtyTrimString, nil, 16)/10)
       return qtyValue
    }

谢谢


阅读 439

收藏
2020-07-07

共1个答案

一尘不染

<44fa0000>是二进制浮点数的 big-endian
内存表示形式2000.0。要从数据中获取数字,您必须UInt32先将其读入,从big-endian转换为主机字节序,然后将结果转换为a
Float

Swift 2

func floatValueFromData(data: NSData) -> Float {
    return unsafeBitCast(UInt32(bigEndian: UnsafePointer(data.bytes).memory), Float.self)
}

例:

let bytes: [UInt8] =  [0x44, 0xFA, 0x00, 0x00]
let data = NSData(bytes: bytes, length: 4)

print(data) // <44fa0000>
let f = floatValueFromData(data)
print(f) // 2000.0

Swift 3中, 您可以使用Data代替NSData,而 unsafeBitCast
可以用Float(bitPattern:) 初始化程序代替:

func floatValue(data: Data) -> Float {
    return Float(bitPattern: UInt32(bigEndian: data.withUnsafeBytes { $0.pointee } ))
}

Swift 5中
,使用(untyped)调用闭包的withUnsafeBytes()方法,您可以从原始内存中获取值:Data``UnsafeRawBufferPointer``load()

func floatValue(data: Data) -> Float {
    return Float(bitPattern: UInt32(bigEndian: data.withUnsafeBytes { $0.load(as: UInt32.self) }))
}
2020-07-07