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

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

本文介绍了如何快速将字节转换为浮点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我将字节数据转换为浮点数的代码.我尝试了这个网站上给出的每一个答案.我得到这个<44fa0000>"字节数据的指数值

This is my code to convert byte data to float. I tried every answers given in this site. I am getting exponential value for this "<44fa0000>" byte data

    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
    }

谢谢

推荐答案

<44fa0000>big-endian 的内存表示二进制浮点数2000.0.从那里取回号码数据,您必须先将其读入 UInt32,从big-endian 托管字节序,然后将结果转换为浮点数.

<44fa0000> is the big-endian memory representation of thebinary floating point number 2000.0. To get the number back fromthe data, you have to read it into an UInt32 first, convert frombig-endian to host byteorder, and then cast the result toa 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:)初始化器:

In Swift 3 you would use Data instead of NSData, and theunsafeBitCast can be replaced by the Float(bitPattern:)initializer:

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

Swift 5 中,DatawithUnsafeBytes() 方法使用(无类型的)UnsafeRawBufferPointer 调用闭包,并且您可以 load() 原始内存中的值:

In Swift 5 the withUnsafeBytes() method of Data calls the closure with an (untyped) UnsafeRawBufferPointer, and you can load() the value from the raw memory:

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

这篇关于如何快速将字节转换为浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:13