最近比较懒啥都不说了直接上代码
OC
NSString *str;
NSData *data;
Byte byte[n];
// 1. NSString -> NSData
data = [str dataUsingEncoding:NSUTF8StringEncoding];
// 2. NSData -> NSString
str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 3. NSString -> Byte
[str getBytes:byte maxLength:str.length usedLength:nil encoding:NSUTF8StringEncoding options:NSStringEncodingConversionExternalRepresentation range:NSMakeRange(0, str.length) remainingRange:nil];
// 4. Byte -> NSString
str = [[NSString alloc] initWithBytes:byte length:sizeof(byte) encoding:NSUTF8StringEncoding];
// 5. NSData -> Byte
(1) const Byte *byteP = data.bytes;
(2) [data getBytes:byte length:sizeof(byte)];
// 6. Byte -> NSData
data = [NSData dataWithBytes:byte length:sizeof(byte)];
Swift
var str: String!
var data: Data!
var uInt8: [UInt8]!
// 1. String -> Data
data = str.data(using: .utf8)
// 2. Data -> String
str = String(data: data, encoding: .utf8)
// 3. String -> [UInt8]
uInt8 = [UInt8](str.utf8)
// 4. [UInt8] -> String
str = String(bytes: uInt8, encoding: .utf8)
// 5. Data -> [UInt8]
uInt8 = [UInt8](data)
(1): Data -> UnsafePointer<UInt8>
_ = data.withUnsafeBytes { (uInt8: UnsafePointer<UInt8>) -> ResultType in
...
}
(2): Data -> UnsafeMutablePointer<UInt8>
data.copyBytes(to: &uInt8, count: uInt8.count)
(3): UnsafeRawPointer -> UnsafePointer<UInt8>
let nsData: NSData = ...
let uInt8P = nsData.bytes.assumingMemoryBound(to: UInt8)
// 6. [UInt8] -> Data
data = Data(bytes: uInt8)