Search code examples
iosswiftfloating-pointbytensmutabledata

How to convert bytes to a float value in swift?


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
    }

Thanks


Solution

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