0

I referred C# code for byte array to string conversion in swift

System.Text.Encoding.UTF8.GetString(encryptedpassword)

I tried to convert byte array to string by using below few codes:

(A)

 let utf8 : [UInt8] = [231, 13, 38, 246, 234, 144, 148, 111, 174, 136, 15, 61, 200, 186, 215, 113,0]
 let str = NSString(bytes: utf8, length: utf8.count, encoding: String.Encoding.utf8.rawValue)
 print("str : \(str)")

result : getting nil value

(B)

 let datastring = NSString(bytes: chars, length: count, encoding: String.Encoding.utf8.rawValue)
 print("string byte data\(chars.map{"\($0)"}.reduce(""){$0+$1})")

result : 23113382462341441481111741361561200186215113 (I thought this is not ideal way)

I searched from last two days and tried other multiple ways but I missed something or doing some mistake . Please help me out resolved this issue.

Referred links: how-to-convert-uint8-byte-array-to-string-in-swift

how-to-convert-uint8-byte-array-to-string-in-swift 2

23
  • 1
    That's certainly not a readable UTF8 string? You might first decrypt it. Commented Apr 10, 2019 at 12:14
  • You are right UTF8 encoding not readable but in C# they pass byte array encryptedpassword into GetString() with encoding UTF8.Is there any alternate way in swift ? Commented Apr 10, 2019 at 12:23
  • 1
    As long as the string is not UTF8 compatible you have to deal with raw Data. You can convert [UInt8] to data simply with let data = Data(utf8) Commented Apr 10, 2019 at 12:28
  • 1
    No, you can't. Please read my comments carefully. Once again you can't because it's not an UTF8 string. Commented Apr 10, 2019 at 12:51
  • 1
    Yes, of course: Data(utf8).base64EncodedString() Commented Apr 10, 2019 at 13:05

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.