Search code examples
swiftfloating-pointintbyte

How to convert a float value to byte array in swift?


The code which I am using for getting data in bytes, but I am not getting correct byte data for float value

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)

Solution

  • Float to NSData:

    var float1 : Float = 40.0
    let data = NSData(bytes: &float1, length: sizeofValue(float1))
    print(data) // <00002042>
    

    ... and back to Float:

    var float2 : Float = 0
    data.getBytes(&float2, length: sizeofValue(float2))
    print(float2) // 40.0
    

    (The same would work for other "simple" types like Double, Int, ...)

    Update for Swift 3, using the new Data type:

    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
    

    (See also round trip Swift number types to/from Data)

    Update for Swift 4 and later:

    var float1 : Float = 40.0
    let data = Data(buffer: UnsafeBufferPointer(start: &float1, count: 1))
    
    let float2 = data.withUnsafeBytes { $0.load(as: Float.self) } 
    print(float2) // 40.0
    

    Remark: load(as:) requires the data to be properly aligned, for Float that would be on a 4 byte boundary. See e.g. round trip Swift number types to/from Data for other solutions which work for arbitrarily aligned data.