Convert NSData To String
NSString *MyString = [[NSString alloc] initWithData:MyData encoding:NSUTF8StringEncoding];
[MyString release];
Convert String To NSData
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
Length
if (data.length > 0)
Accessing Individual Bytes
Converting the entire array
UInt8 *bytes = (UInt8 *)data.bytes;
if (data.length >= 4)
NSLog(@"Byte0: %d, Byte1: %d, Byte2: %d, Byte3: %d", bytes[0], bytes[1], bytes[2], bytes[3]);
Getting selected bytes
UInt8 DataBytes[4];
[FileData getBytes:DataBytes range:NSMakeRange(0, 4)]; //Get 4 bytes from index 0
NSLog(@"Data: %d %d %d %d", DataBytes[0], DataBytes[1], DataBytes[2], DataBytes[3]);
Create NSData From File
NSData *data = [NSData dataWithContentsOfFile:filePath];
Create NSData From String
NSData *TxData = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
Create NSData From Byte Array
UInt8 TxDataBytes[10];
int TxDataIndex = 0;
TxDataBytes[TxDataIndex++] = 0x01;
TxDataBytes[TxDataIndex++] = 0x02;
TxDataBytes[TxDataIndex++] = 0x03;
TxDataBytes[TxDataIndex++] = 0x04;
NSData *TxData = [NSData dataWithBytes:&TxDataBytes length:TxDataIndex];
Copy Data To Array
NSMutableArray *ReceivedData = (NSMutableArray *)[data bytes];
Append NSData to NSData
You need to use NSMutableData so you can append:
NSString *response = [NSString stringWithFormat:@"Hello"];
NSMutableData *data = [[NSMutableData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[data appendData:[NSData GetBlockOfDataFromFile:MyFilePath atOffset:MyOffset withSize:MyLength]];
...
[data release];
Remove Bytes From NSData
You need to use NSMutableData
//Removing from the end
[MyData setLength:[MyData length] - 4]; //Remove 4 bytes from the end
//Removing from the beginning
[MyData replaceBytesInRange:NSMakeRange(0, 4) withBytes:NULL length:0]; //Remove 4 bytes from the start
//Removing from the middle
[MyData replaceBytesInRange:NSMakeRange(6, 4) withBytes:NULL length:0]; //Remove 4 bytes after the first 6 bytes
Create Large Array Of NSMutableData
//Create array of data values
UInt8 DataBytes[4];
NSMutableData *FileData = [[NSMutableData alloc] init];
UInt32 DataIndex = 0;
for (DataIndex = 0; DataIndex < (1024 * 1024 * 2); DataIndex += 4)
{
DataBytes[0] = (Byte)((DataIndex & 0xff000000) >> 24);
DataBytes[1] = (Byte)((DataIndex & 0x00ff0000) >> 16);
DataBytes[2] = (Byte)((DataIndex & 0x0000ff00) >> 8);
DataBytes[3] = (Byte)(DataIndex & 0x000000ff);
[FileData appendBytes:DataBytes length:4];
}
...
[FileData release];