How to convert NSString to bytes

2019-01-25 06:16发布

问题:

NSString *test = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";

How to convert this string to bytes?

回答1:

NSData *bytes = [test dataUsingEncoding:NSUTF8StringEncoding];


回答2:

Do you want something like this:

NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%i bytes", bytes);


回答3:

extension String {
    var byteArray : [Byte] {
        return Array(utf8)
    }
}

update: Xcode 7.2.1 • Swift 2.1.1

extension String {
    var byteArray : [UInt8] {
        return Array(utf8)
    }
}

testing:

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".byteArray  // [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]


标签: nsstring