iosswiftaccelerate-frameworkvdsp

Convert single-precision, floating-point value to Int 16 using Accelerate framework


How to convert single precision floating-point to int 16 with help of Accelerate framework.

Int16 to float:

import Accelerate

let rr: [Int16] = [ 18, 21, 41, 42, 48, 50, 55, 90]

var float = [Float](repeating: 0, count: rr.count)

vDSP_vflt16(rr, 1, &float, 1, vDSP_Length(rr.count)) 

now i'm try to revert it Float to Int16 ?


Solution

  • You could use vDSP_vfix16 :

    var ints = [Int16](repeating: 0, count: rr.count)
    
    vDSP_vfix16(float, 1, &ints, 1, vDSP_Length(float.count))
    
    print(ints)
    
    // [18, 21, 41, 42, 48, 50, 55, 90]
    

    vDSP_vfix16 rounds towards 0. You can find other functions that use other rounding rules in the "Single-Vector Floating Point to 16-Bit Integer Conversion" section here.