iOS 中NSString NSData char*数据类型之间转换


1. NSString转化为UNICODE String:

(NSString*)t = @”字符串”;
char t2[10];
memcpy(t2, [fname cStringUsingEncoding:NSUnicodeStringEncoding], 2*([t length]));
与strcpy相比,memcpy并不是遇到’\0’就结束,而是一定会拷贝完n个字节


2. NSString 转化为 char *

NSString @t= @”字符串”;
const char *t2 =[t UTF8String];


3.char * 转化为 NSString

char *t2 =”testInformation”;
NSString *t = [[NSString alloc]initWithCString:t2 encoding:NSUTF8StringEncoding];


4. char * 转化 NSData

方法一:
char * t = (char*)malloc(sizeof(byte)*16);
NSData *t2 = [NSData dataWithBytes:t length:strlen(t)];
方法二:
转换为NSString: – (id)initWithUTF8String:(const char *)bytes
然后用NSString的 – (NSData *)dataUsingEncoding:(NSStringEncoding)encoding


5. NSData 转化 char *

NSData t2 ;
char* t=[t2 bytes];


6. NSData 转化 NSString;

NSData* t;
NSString* t2= [NSString alloc] initWithData:t encoding:NSASCIIStringEncoding];


7. NSString 转化 NSData对象

NSData* t2 = [@”t2″ dataUsingEncoding:NSUTF8StringEncoding];