iphoneobjective-ccfreadstream

How to extract only the 1st 2 bytes of data from CFReadStream in Objective-C for iPhone programming


  1. How can I read the data from read stream in Objective-C? The code below would give me how many bytes are read from stream, but how can I know what data is read from stream?

    CFIndex cf = CFReadStreameRead(Stream, buffer, length);
    
  2. How can I extract only the 1st 2bytes of data in the read stream in Objective-C? For example, if this is the data from stream:

    017MacApp
    

    1st byte has 0 in it, and 2nd byte has 17 in it.

    How do I extract 0 and 17 into byte array?

I know that the below code would give me back the byte array to int value.

((b[0] & 0xFF) << 8)+ (b[1] & 0xFF);

but how to put 0 into b[0] and 17 into b[1]?


Solution

  • uint8_t buffer[2];
    CFIndex cf = CFReadStreamRead(Stream, buffer, 2);
    if (cf == 2)
    {
        uint8_t firstByte = buffer[0];
        uint8_t secondByte = buffer[1];
    }
    else
    {
        // cf == -1 => error, cf == 0 => end of file, cf == 1 => you need to call again to get the second byte
    }
    

    Here is the Apple doc.