欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

NSString、NSData、char相互转换

程序员文章站 2022-03-27 10:25:39
NSString 转换成NSData 对象NSData* newData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding]; NSData 转换成NSString对象NSData * data; NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 在iOS底层网络的开发中,会遇到NSData 转 NSSt...

NSString 转换成NSData 对象

NSData* newData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding]; 

NSData 转换成NSString对象

NSData * data; 
NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding]; 

在iOS底层网络的开发中,会遇到NSData 转 NSString 为空的情况,原因很多,下面的解决方法是针对从服务器传过来的数据中含有非UTF-8字符(主要是UTF-8)的情况。

用libiconv清除非utf8字符
先给项目Link Binaries With Library 添加libiconv.dylib
使用如下函数对NSData进行清理,再进行转换就OK了

-(NSData *)cleanUTF8:(NSData *)data {
  iconv_t cd = iconv_open("UTF-8", "UTF-8"); // 从utf8转utf8
  int one = 1;
  iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, &one); // 丢弃不正确的字符
 
  size_t inbytesleft, outbytesleft;
  inbytesleft = outbytesleft = data.length;
  char *inbuf  = (char *)data.bytes;
  char *outbuf = malloc(sizeof(char) * data.length);
  char *outptr = outbuf;
  if (iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft)
      == (size_t)-1) {
    NSLog(@"this should not happen, seriously");
    return nil;
  }
  NSData *result = [NSData dataWithBytes:outbuf length:data.length - outbytesleft];
  iconv_close(cd);
  free(outbuf);
  return result;
}

NSData 转换成char*

NSData *data; 
char *test=[data bytes];

char* 转换成NSData对象

byte* tempData = malloc(sizeof(byte)*16); 
NSData *content=[NSData dataWithBytes:tempData length:16];

 NSString 转 char *

1. UTF8String

const char *cString = [string UTF8String];

2. cStringUsingEncoding:

const char *cString = [string cStringUsingEncoding:NSUTF8StringEncoding];

3. getCString:maxLength:encoding:

char cStringPtr[string.length * 3 + 1];
memset(cStringPtr, 0, sizeof(cStringPtr));
[string getCString:cStringPtr maxLength:sizeof(cStringPtr) encoding:NSUTF8StringEncoding];

UTF8编码需要占用3个字节,因此这里需要*3

 char* 转 NSString

1. initWithUTF8String:

NSString *string = [[NSString alloc] initWithUTF8String:cString];

2. initWithCString:encoding:

NSString *string = [[NSString alloc] initWithCString:cString encoding:NSUTF8StringEncoding];

3. stringWithFormat:

NSString *string = [NSString stringWithFormat@"%s", cString];

本文地址:https://blog.csdn.net/u012094456/article/details/107149298