0

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

3

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

0

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)

1 Comment

You can use Array.init(unsafeUninitializedCapacity:initializingWith:) to prevent the need of writing all those 0s over the destination arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.