How to convert array of Int8 to array of Float again revert it.
I have function to filter float data, so i need to first convert it to [Float] and process it and again convert it to [Int8] and feed it
How to convert array of Int8 to array of Float again revert it.
I have function to filter float data, so i need to first convert it to [Float] and process it and again convert it to [Int8] and feed it
map is your friend. You have 2 approaches using this function:
1.
let myArray: [UInt8] = [1, 2, 3, 4, 5]
let processedArray = myArray.map { element in
let floatElement = Float(element)
// process float
return Int8(floatElement)
}
2.
let myArray: [UInt8] = [1, 2, 3, 4, 5]
let processedArray = myArray
.map { Float($0) } // convert to Float
.map { operation($0) } // process the float & return a float
.map { UInt8($0) } // reconvert to UInt8
Both are equivalent, but I think the second option is more readable and allows for a bit more flexibility. It's a matter of preference.
extension Array where Iterator.Element == Int8 {
var toFloatArray: [Float] {
return self.map({Float($0)})
}
}
extension Array where Iterator.Element == Float {
var toIntArray: [Int8] {
return self.map({Int8($0)})
}
}
let myIntArr: [Int8] = [1,2,4]
let myFloatArr: [Float] = myIntArr.toFloatArray
print(myFloatArr)
let newIntArr = myFloatArr.toIntArray
print(newIntArr)
Use extensions for clean reusable code.
Ok I Got it thanks @ Martin R
let rr: [Int8] = [ 18, 21, 41, 42, 48, 50, 55, 90]
var float = [Float](repeating: 0, count: rr.count)
vDSP_vflt8(rr, 1, &float, 1, vDSP_Length(rr.count))
var ints = [Int8](repeating: 0, count: rr.count)
vDSP_vfix8(float, 1, &ints, 1, vDSP_Length(float.count))
print(ints)
Array.init(unsafeUninitializedCapacity:initializingWith:) to prevent the need of writing all those 0s over the destination arrays.