10

I have decrypted using AES (CrytoSwift) and am left with an UInt8 array. What's the best approach to covert the UInt8 array into an appripriate string? Casting the array only gives back a string that looks exactly like the array. (When done in Java, a new READABLE string is obtained when casting Byte array to String).

0

4 Answers 4

11

I'm not sure if this is new to Swift 2, but at least the following works for me:

let chars: [UInt8] = [ 49, 50, 51 ]
var str = String(bytes: chars, encoding: NSUTF8StringEncoding)

In addition, if the array is formatted as a C string (trailing 0), these work:

str = String.fromCString(UnsafePointer(chars)) // UTF-8 is implicit
      // or:
str = String(CString: UnsafePointer(chars), encoding: NSUTF8StringEncoding)
Sign up to request clarification or add additional context in comments.

2 Comments

I tried the above suggestion but it always comes out as nil. Am I missing something?
@jaytrixz Copypasting the first two lines (only) directly into Swift playground works fine for me. The last two lines don't work for the example array, because (as mentioned in the answer), it needs to be NUL-terminated (i.e., a C string). Changing the array contents to [ 49, 50, 51, 0 ] makes them work.
3

I don't know anything about CryptoSwift. But I can read the README:

For your convenience CryptoSwift provides two function to easily convert array of bytes to NSData and other way around:

let data  = NSData.withBytes([0x01,0x02,0x03])
let bytes:[UInt8] = data.arrayOfBytes()

So my guess would be: call NSData.withBytes to get an NSData. Now you can presumably call NSString(data:encoding:) to get a string.

Comments

3

SWIFT 3.1 Try this:

let decData = NSData(bytes: enc, length: Int(enc.count))
let base64String = decData.base64EncodedString(options: .lineLength64Characters)  

This is string output

Comments

0

Extensions allow you to easily modify the framework to fit your needs, essentially building your own version of Swift (my favorite part, I love to customize). Try this one out, put at the end of your view controller and call in viewDidLoad():

func stringToUInt8Extension() {
    var cache : [UInt8] = []
    for byte : UInt8 in 97..<97+26 {
        cache.append(byte)
        print(byte)
    }
    print("The letters of the alphabet are \(String(cache))")
}

extension String {
    init(_ bytes: [UInt8]) {
        self.init()
        for b in bytes {
            self.append(UnicodeScalar(b))
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.