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

653 Views Asked by At

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 ?

2

There are 2 best solutions below

0
ielyamani On BEST ANSWER

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.

1
Flex Monkey On

There's also floatingPointToInteger in the vDSP Swift Overlay:

let floats: [Float] = [ 18, 21, 41, 42, 48, 50, 55, 90]

let ints = vDSP.floatingPointToInteger(floats,
                                       integerType: Int16.self,
                                       rounding: .towardNearestInteger)

print(ints) // Prints "[18, 21, 41, 42, 48, 50, 55, 90]"