NSString转NSData

NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];

NSData转NSString

NSString *aString = [[NSString alloc] initWithData:adataencoding:NSUTF8StringEncoding];


NSData转UIImage

UIImage *aimage = [UIImage imageWithData: imageData];


沙盒图片转为NSData示例

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *name = [NSString stringWithFormat:@"ceshi.png"];
NSString *finalPath = [path stringByAppendingPathComponent:name];
NSData *imageData = [NSData dataWithContentsOfFile: finalPath];
UIImage *aimage = [UIImage imageWithData: imageData];


填充截取NSData

//填充数据  
NSData *appData=[[NSData alloc] init];//要填充的数据
[mData appendData:appData];

//获取数据
Byte b0 = ((Byte*)([mData bytes]))[0];//获取某一位置的数据
NSData *subData =[mData subdataWithRange:NSMakeRange(0, 100)];//截取索引0到索引100的数据
//截取数据
NSData *subData =[mData subdataWithRange:NSMakeRange(0, 100)];//截取索引0到索引100的数据
//删除数据
[mData replaceBytesInRange:NSMakeRange(0, 50) withBytes:NULL length:0];//删除索引0到索引50的数据


char * 转 NSData

const char * string = "Hi there ,this is a C string";  
//建立缓冲区,把字符串添加进去
NSData * data = [NSData dataWithBytes:string length:strlen(string)+1];
//输出
NSLog(@"data is %@",data);
NSLog(@"%lu bytes string is '%s'",[data length],[data bytes]);


byte数组转NSData 


Byte array[] = {0, 0, 0, 0};
NSData *data = [NSData dataWithBytes: array length: sizeof(array)];

NSData转Byte数组


NSData *testData = [@“测试数据” dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];


定义16进制字符串

NSString* str = [NSString stringWithFormat:@"%d", 0x0a];

综合示例

void* buffer_head=malloc(2);
void* buffer = malloc(512);
NSInteger len = 0;
NSInteger head_len=0;
NSMutableData *packet = [[NSMutableData alloc] init];
NSData *line;
NSInteger totalLength = 0;
while ([reader hasBytesAvailable]) { //reader是输入流
if(_hasHead){
//获取头两个字节
head_len = [reader read:buffer_head maxLength:2 ];
const uint8_t * bytes =(constuint8_t *) buffer_head;
int first = bytes[0];
int second=bytes[1];
int addtion=first*16+second;
//两字节组合
//按头长度的需求读取指定字节后退出循环
len = [reader read : buffer maxLength : addtion];
if(len==-1)continue;
// copy the bytes to the mutable buffer and update the total length
[packet appendBytes : buffer length:len];
totalLength = totalLength + len;
} else{
len=[reader read:buffer maxLength:sizeof(buffer)];
[packet appendBytes:buffer length:len];
totalLength = totalLength + len;
}
// 截取数据
line = [packet subdataWithRange:NSMakeRange(0, totalLength)];
}

NSString转换为unsigned long

NSString *str = @"0xff055008";  
//先以16为参数告诉strtoul字符串参数表示16进制数字,然后使用0x%X转为数字类型
unsigned long red = strtoul([str UTF8String],0,16);
//strtoul如果传入的字符开头是“0x”,那么第三个参数是0,也是会转为十六进制的,这样写也可以:
unsigned long red = strtoul([@"0x6587" UTF8String],0,0);
NSLog(@"转换完的数字为:%lx",red);