简体   繁体   中英

How to read bytes from NSData

任何人都可以建议一种从NSData读取字节的方法(例如@interface NSInputStream读取函数: NSStream

How to read binary bytes in NSData? may help you:

NSString *path = @"…put the path to your file here…";
NSData * fileData = [NSData dataWithContentsOfFile: path];
const char* fileBytes = (const char*)[fileData bytes];
NSUInteger length = [fileData length];
NSUInteger index;

for (index = 0; index<length; index++) {
   char aByte = fileBytes[index];
   //Do something with each byte
}

You can also create an NSInputStream from an NSData object, if you need the read interface:

NSData *data = ...;
NSInputStream *readData = [[NSInputStream alloc] initWithData:data];
[readData open];

However, you should be aware that initWithData copies the contents of data.

One of the simplest ways is to use NSData getBytes:range: .

NSData *data = ...;
char buffer[numberOfBytes];
[data getBytes:buffer range:NSMakeRange(position, numberOfBytes)];

where position and length is the position you want to read from in NSData and the length is how many bytes you want to read. No need to copy.

Alex already mentioned NSData getBytes:range: but there is also NSData getBytes:length: which starts from the first byte.

NSData *data = ...;
char buffer[numberOfBytes];
[data getBytes:buffer length:numberOfBytes];

May way of doing that.. do not forget to free byte array after usage.

NSData* dat = //your code
NSLog(@"Receive from Peripheral: %@",dat);
NSUInteger len = [dat length];
Byte *bytedata = (Byte*)malloc(len);
[dat getBytes:bytedata length:len];
int p = 0;
while(p < len)
{
    printf("%02x",bytedata[p]);
    if(p!=len-1)
    {
     printf("-");
    }//printf("%c",bytedata[p]);
    p++;
}
printf("\n");
// byte array manipulation

free(bytedata);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM