Base64 Encoded String from Array of Uint64 in Swift - swift

How can I create a base64 encoded string from 4 UInt64 integers?
I presume there are a few steps to this that i'm not sure how to approach, such as combing integers, converting to binary, or perhaps constructing string using some loop over integers?
I'd appreciate any code example or pointers on how to achieve this.

It this what you want?
func base64String(integers: [UInt64]) throws -> String {
let data = try JSONEncoder().encode(integers)
let string = data.base64EncodedString()
return string
}
// call
let result = try? base64String(integers: [234, 23, 3, 1002, 3])

Related

Parsing Data Out of Dictionary<String, Any> in Swift

I'm trying to extract data out of a Dictionary<String, Any> in Swift. The dictionary returns the following when I run NSLog("\(terminalDict)"):
Optional(["DFEE22": <323c3c>, "DFEE20": <3c>, "DFEE21": <0a>, "DFEE17": <07>, "DFEE1E": , "DF10": <656e6672 65737a68>, "9F1C": <38373635 34333231>, "DFEE16": <00>, "DFEE15": <01>, "5F36": <02>, "DF11": <00>, "DFEE1F": <80>, "DFEE18": <80>, "9F1A": <0840>, "9F35": <21>, "9F4E": <31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e>, "DF27": <00>, "DFEE1B": <30303031 35313030>, "DF26": <01>, "9F15": <1234>, "9F40": <f000f0a0 01>, "9F16": <30303030 30303030 30303030 303030>, "9F33": <6028c8>, "9F1E": <5465726d 696e616c>])
I want to get all the keys and values out of the dictionary and into one string variable (newSettings). This is how I was attempting to do that:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
NSLog("value is now= \(value)")
let asString = value as! String
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}
which returns:
key is now= DFEE22
value is now= {length = 3, bytes = 0x323c3c}
Could not cast value of type 'NSConcreteMutableData' (0x204aff148) to 'NSString' (0x204afde30).
How can I get the "323c3c" out of the dictionary as a simple string without the length and bytes portion? I can't find much documentation on type 'NSConcreteMutableData'. Do I have to use substring functions in order to get rid of the "length=x bytes=" part? I'm guessing there's a better way to do this than manually getting the substrings. Thanks.
As Vadian says, your dictionaries contain Data values.
It looks like it is ASCII encoded text, but it's a bit hard to be sure.
This bit:
31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e
Represents the string "10721 Walker St. Cypress, CA ,USA." when you treat it as ASCII.
you could use code like this:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
// Decode the data into a String assuming it's ASCII
let asString = String(data: value, encoding: .ascii)
NSLog("value is now= '\(asString)'")
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}

Array (Inside of a String) Conversion, Swift 4

Does anyone know the simplest way to convert an Array inside of a String to an actual Array without effecting any characters?
For Example:
var array: [String] = []
let myStr = "[\"Hello,\", \"World\"]"
// I would like 'array' to store: ["Hello,", "World"]
I thought it could be done with Array(myStr) but that would only make an array of all the characters.
Help would be appreciated. Thank you.
You can decode it with JSONDecoder, since it is a JSON.
Example below:
let myStr = "[\"Hello,\", \"World\"]"
let data = Data(myStr.utf8)
do {
let decoded = try JSONDecoder().decode([String].self, from: data)
print("Decoded:", decoded)
} catch {
fatalError("Error")
}
// Prints: Decoded: ["Hello,", "World"]
What is happening:
Your myStr string is converted to Data.
This data is then decoded as [String] - which is an array of strings.
The decoded data of type [String] is then printed.
We use a do-try-catch pattern to catch errors, such as incorrect format or data entered.

Swift3: Proper way to convert string to null-terminated C-string

I am interfacing with libxml2 in swift, and the C APIs binding (still) produce UnsafePointer<Int8>! for c-strings. Whereas Swift APIs normally result in UnsafePointer<UInt8>!.
So my question is - am I doing the string to null-terminated C-string in a proper way?
let cfilePath = unsafeBitCast(myStringString.nulTerminatedUTF8.withUnsafeBufferPointer { $0.baseAddress }, to: UnsafePointer<Int8>.self)
Should I instead prefer using some other method instead of just bypassing Swift type checking with interpreting UInt8 bytes as Int8 bytes?
I'm not sure this solves your problem exactly but for a project where I am sending strings over bluetooth this did the trick:
extension String {
var nullTerminated: Data? {
if var data = self.data(using: String.Encoding.utf8) {
data.append(0)
return data
}
return nil
}
}
Use like this
let data = "asfasf".nullTerminated
I can't find the function the other answers are referencing: nulTerminatedUTF8. Maybe it already does this.
don't use unsafeBitCast for that!!
let cstr = "alpha".nulTerminatedUTF8
let int8arr = cstr.map{ Int8(bitPattern: $0) }
let uint8arr = Array(cstr)
print(int8arr.dynamicType, uint8arr.dynamicType)
// Array<Int8> Array<UInt8>
update
let uint8: UInt8 = 200
let int8 = Int8(bitPattern: uint8)
print(uint8, int8)
// 200 -56

Convert UInt8 Array to String

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).
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)
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.
SWIFT 3.1
Try this:
let decData = NSData(bytes: enc, length: Int(enc.count))
let base64String = decData.base64EncodedString(options: .lineLength64Characters)
This is string output
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))
}
}
}

Swift: How to convert a String to UInt8 array?

How do you convert a String to UInt8 array?
var str = "test"
var ar : [UInt8]
ar = str
Lots of different ways, depending on how you want to handle non-ASCII characters.
But the simplest code would be to use the utf8 view:
let string = "hello"
let array: [UInt8] = Array(string.utf8)
Note, this will result in multi-byte characters being represented as multiple entries in the array, i.e.:
let string = "é"
print(Array(string.utf8))
prints out [195, 169]
There’s also .nulTerminatedUTF8, which does the same thing, but then adds a nul-character to the end if your plan is to pass this somewhere as a C string (though if you’re doing that, you can probably also use .withCString or just use the implicit conversion for bridged C functions.
let str = "test"
let byteArray = [UInt8](str.utf8)
swift 4
func stringToUInt8Array(){
let str:String = "Swift 4"
let strToUInt8:[UInt8] = [UInt8](str.utf8)
print(strToUInt8)
}
I came to this question looking for how to convert to a Int8 array. This is how I'm doing it, but surely there's a less loopy way:
Method on an Extension for String
public func int8Array() -> [Int8] {
var retVal : [Int8] = []
for thing in self.utf16 {
retVal.append(Int8(thing))
}
return retVal
}
Note: storing a UTF-16 encoded character (2 bytes) in an Int8 (1 byte) will lead to information loss.