Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UInt8 Array to String

Tags:

swift

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

like image 471
Min Tseng Avatar asked Jul 23 '15 01:07

Min Tseng


People also ask

What is a Uint 8 array?

The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Is Uint8Array same as byte array?

Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”. Uint16Array – treats every 2 bytes as an integer, with possible values from 0 to 65535.

How do I encode Uint8Array?

var u8 = new Uint8Array([65, 66, 67, 68]); var decoder = new TextDecoder('utf8'); var b64encoded = btoa(decoder. decode(u8)); If you need to support browsers that do not have TextDecoder (currently just IE and Edge), then the best option is to use a TextDecoder polyfill.

What does buffer from do?

The Buffer. from() method is used to create a new buffer containing the specified string, array or buffer.


2 Answers

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)
like image 111
Arkku Avatar answered Sep 17 '22 19:09

Arkku


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.

like image 22
matt Avatar answered Sep 20 '22 19:09

matt