Reputation: 3469
NSString *test = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
How to convert this string to bytes?
Upvotes: 17
Views: 27668
Reputation: 236360
Swift 1.x
extension String {
var bytes: [Byte] {
return Array(utf8)
}
}
Swift 2.1.1
extension String {
var bytes : [UInt8] {
return Array(utf8)
}
}
Xcode 9 • Swift 4 or later
extension StringProtocol {
var bytes: [UInt8] { return .init(utf8) }
var data: Data { return .init(utf8) }
}
Xcode 11 • Swift 5.1 or later
extension StringProtocol {
var bytes: [UInt8] { .init(utf8) }
var data: Data { .init(utf8) }
}
testing:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".bytes // [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
Upvotes: 2
Reputation: 5969
Do you want something like this:
NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%i bytes", bytes);
Upvotes: 4