Question

i have a size_tvariable i would display in a NSLog. This variable contains the number of bytes sent.

if i use this: NSLog(@"%zu",myvariable); i have no error message but the number overflows and the NSLog output keeps showing numbers below 32.768. why is that? isnt Long supposed to show values ranging in value from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 ?

here is some code. i want to show in NSlog self.bufferOffset, that should be the approx ammount of bytes sent.

        // If we don't have any data buffered, go read the next chunk of data.

        if (self.bufferOffset == self.bufferLimit) {
            NSInteger   bytesRead;

            bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];

            if (bytesRead == -1) {
                [self stopSendWithStatus:@"File read error"];
            } else if (bytesRead == 0) {
                [self stopSendWithStatus:nil];
            } else {
                self.bufferOffset = 0;
                self.bufferLimit  = bytesRead;
            }
        }

        // If we're not out of data completely, send the next chunk.

        if (self.bufferOffset != self.bufferLimit) {
            NSInteger   bytesWritten;
            bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
            assert(bytesWritten != 0);
            if (bytesWritten == -1) {
                [self stopSendWithStatus:@"Network write error"];
            } else {
                self.bufferOffset += bytesWritten;
            }

        }

             NSLog (@"%lu",self.bufferOffset);

and here is some of the output:

  2013-02-24 15:54:39.674 prog[298:303] 32768
  2013-02-24 15:54:39.728 prog[298:303] 4820
  2013-02-24 15:54:39.791 prog[298:303] 10820
  2013-02-24 15:54:39.853 prog[298:303] 16580
  2013-02-24 15:54:39.911 prog[298:303] 23780
  2013-02-24 15:54:39.965 prog[298:303] 28100
  2013-02-24 15:54:40.024 prog[298:303] 32768
  2013-02-24 15:54:40.080 prog[298:303] 6852
  2013-02-24 15:54:40.139 prog[298:303] 14052
  2013-02-24 15:54:40.197 prog[298:303] 18372
Was it helpful?

Solution

self.bufferOffset in your code is the offset of the first read-but-not-yet-written byte in the buffer, therefore you will always have

 self.bufferOffset <= kSendBufferSize

This (hopefully) explains why the NSLog() output is limited by 32768.

self.bufferOffset is not the total number of bytes written.

Remark: As others already have commented, the %zu format works correctly with a size_t variable. On a 64-bit platform, size_t is a 64-bit unsigned integer. Example:

size_t s = 18446744073709551615ULL; // 2^64-1
NSLog(@"%zu", s);
// Output: 18446744073709551615
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top