NSString -> NSData
- (NSData *)castAsData {
const char *chars = [self UTF8String];
int i = 0;
NSMutableData *data = [NSMutableData dataWithCapacity:self.length / 2];
char byteChars[3] = {'\0', '\0', '\0'};
unsigned long wholeByte;
while (i < self.length) {
byteChars[0] = chars[i++];
byteChars[1] = chars[i++];
wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}
return data;
}
複製程式碼
Byte -> NSData
+ (NSData *)castByte:(Byte *)byte {
NSData *data = [[NSData alloc] initWithBytes:byte length:sizeof(byte)];
return data;
}
複製程式碼
NSData -> NSString(hex)
- (NSString *)castAsString {
const unsigned char *dataBuffer = (const unsigned char*)[self bytes];
if (!dataBuffer) {
return [NSString string];
}
NSUInteger dataLength = self.length;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
NSString *hex = [[NSString stringWithFormat:@"%2lx", (unsigned long)dataBuffer[i]] stringByReplacingOccurrencesOfString:@" " withString:@"0"];
[hexString appendString:hex];
}
return [NSString stringWithString:hexString];
}
複製程式碼