Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to UTF 8

I've currently got a string array and I want to convert this to a UInt8 array? All of the strings are UInt8's, however I can only retrieve it as a string. Any ideas?

let stringValues = "[185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]"

I have each item in the array split up into its individual part, I just don't know how to convert the string to UInt8.

Thanks

like image 731
Jay Avatar asked Jul 01 '26 00:07

Jay


2 Answers

This works:

var stringValues = "[185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]"

stringValues = stringValues.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "")

var values = [UInt8]()
print(stringValues)
for item in stringValues.componentsSeparatedByString(",") {
    if let value = UInt8(item) {
        values.append(value)
    }
}
like image 70
totiDev Avatar answered Jul 05 '26 16:07

totiDev


let stringValues = "[185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]"
let uint8Values = stringValues.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:" ,\"[]"))
    .filter { !$0.isEmpty}.flatMap{ UInt8($0) }
like image 39
user3441734 Avatar answered Jul 05 '26 15:07

user3441734



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!