NSData的一些直接操作binary data的用法

方法:

//將另一個NSData加到原來的NSData後面
-(void)appendData:(NSData*)otherData

//將bytes直接加入NSData,參數為1.bytes的起始位置(要加&),2.bytes的長度
-(void)appendBytes:(const void*)bytes length:(NSUInteger)length

//截取其中某一段NSData
-(NSData*)subdataWithRange:(NSRange)range

//從你的NSData中copy某段bytes出來,存到你新建的buffer(要加&)中(存數值資料,而非NSData)
-(void)getBytes:(void*)buffer range:(NSRange)range

//從你的NSData中從頭copy某段指定長度的bytes出來,存到你新建的buffer(要加&)中(存數值資料,而非NSData)
-(void)getBytes:(void*)buffer length:(NSUInteger)length

範例

//直接取得binary檔案

NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"yourBinary" withExtension:@"bin"];
NSString *stringPath = [imgPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];

//要把NSData轉回NSNumber時(這裡是以short為範例)
short s;
[yourData getBytes:&s range:range];
NSNumber* stepCount = [NSNumber numberWithUnsignedShort:s];


// low level read method - read data while there is data and space available in the input buffer
- (void)_readData{
    uint8_t buf[EAD_INPUT_BUFFER_SIZE];
    while ([[_session inputStream] hasBytesAvailable]){
        NSInteger bytesRead = [[_session inputStream] read:buf maxLength:EAD_INPUT_BUFFER_SIZE];
        if (_readData == nil){
            _readData = [[NSMutableData alloc] init];
        }
        [_readData appendBytes:(void *)buf length:bytesRead];
        //NSLog(@"read %d bytes from input stream", bytesRead);
 }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:EADSessionDataReceivedNotification object:self userInfo:nil];

    //清空_readData
    if( _readData ){
        [_readData setLength:0];
    }
}

// high level read method
// 這裡輸入的參數為你想要切的長度。

- (NSData *)readData:(NSUInteger)bytesToRead
{
    NSData *data = nil;
    if ([_readData length] >= bytesToRead)
    {
        NSRange range = NSMakeRange(0, bytesToRead);
        data = [_readData subdataWithRange:range];
        [_readData replaceBytesInRange:range withBytes:NULL length:0];
    }
    return data;
}

// get number of bytes read into local buffer

-(NSUInteger)readBytesAvailable{
    return [_readData length];

}

//自己寫的切封包

+ (NSArray*)splitDataIntoChunks:(NSData*)data size:(NSUInteger)bytesPerChunk{
    if(!data) return nil;
    NSMutableArray* array = [[NSMutableArray alloc]init];
    NSUInteger dataLength = [data length];
    NSUInteger chunkCount = 0;
    while (chunkCount < dataLength){
        NSRange range = NSMakeRange(chunkCount, bytesPerChunk);
        NSData* chunk = [data subdataWithRange:range];
        [array addObject:chunk];
        chunkCount += 2;
    }
    return array;
}
2016/12/29 posted in  Foundation