Nisha Nair
Nisha Nair

Reputation: 347

String Array to Int8 Array byte TypeCasting

The code which i am using but it shows an error of cannot invoke initializer for type array with argument list of string.utf8view

Help me to convert a string to signed int byte array

 static func stringToByteArray(string : String)-> Array<Int8> 
  {
        let array: [Int8] = Array(string.utf8)
        //print("string array \(array)")
        return array

    }

Upvotes: 1

Views: 1259

Answers (1)

Himanshu
Himanshu

Reputation: 2832

Use this method that firstly convert your array to unsigned integer then to signed array as there is no method to typecast unsigned array to signed array directly.

 func stringToByteArray(string : String)-> Array<Int8>
    {
        let array: [UInt8] = Array(string.utf8)
        var arraySigned = [Int8]()
        var convertSigned: Int8!
        for element in array
        {
            convertSigned = Int8(bitPattern: element)
            arraySigned.append(convertSigned)
        }

        print("string array \(arraySigned)")
        return arraySigned

    }

Upvotes: 2

Related Questions