How to convert bytes to a float value in swift?

后端 未结 3 1680
悲哀的现实
悲哀的现实 2020-12-16 22:54

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



        
3条回答
  •  悲哀的现实
    2020-12-16 23:49

    <44fa0000> is the big-endian memory representation of the binary floating point number 2000.0. To get the number back from the data, you have to read it into an UInt32 first, convert from big-endian to host byteorder, and then cast the result to a Float.

    In Swift 2 that would be

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

    Example:

    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
    

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

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

    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) }))
    }
    

提交回复
热议问题