objective-c NSData,Int互转

将int转成NSData

    NSString *temp=@"test";
    
    NSData *datatemp =[temp dataUsingEncoding:NSUTF8StringEncoding];
    
    int datatemplength =CFSwapInt32BigToHost((uint32_t)datatemp.length);  //大小端不一样,需要转化
    
    NSData *data = [NSData dataWithBytes: &datatemplength length: sizeof(datatemplength)];
    
    NSMutableData *result=[[NSMutableData alloc]init];
    
    [result appendData:data];
    [result appendData:datatemp];

将NSData转成int

    int datalength;
    
    [result getBytes: &datalength length: sizeof(datalength)];
    
    int length=CFSwapInt32BigToHost(datalength);
    
    NSData *databack = [result subdataWithRange:NSMakeRange(4, length)];


你可能感兴趣的:(iOS开发)