Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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];
                Need to update your code snippet to read:    [data getBytes:buffer length:numberOfBytes];
– pete
                Apr 6, 2021 at 2:26
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]);
printf("\n");
// byte array manipulation
free(bytedata);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.