1

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

    }
3
  • 1
    Possible duplicate of stackoverflow.com/questions/30255402/… Commented May 5, 2016 at 4:53
  • yes i am using that same code but it is for UInt8, i need it for Int8 byte array conversion Commented May 5, 2016 at 4:56
  • why do you want to convert string to signed Int8 array ? Commented May 5, 2016 at 5:21

1 Answer 1

2

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

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

2 Comments

@NishaNair: Don't forget to accept helpful answers!
Simpler: let arraySigned = string.utf8.map { Int8(bitPattern: $0) }

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.