NSString stringWithFormat中的`size_t`

时间:2013-02-24 14:26:39

标签: objective-c cocoa nsstring stringwithformat

我有一个size_t变量,我会在NSLog中显示。此变量包含发送的字节数。

如果我使用它:NSLog(@"%zu",myvariable);我没有错误消息,但数字溢出,NSLog输出保持显示低于32.768的数字。这是为什么? isnt Long应该显示从-9,223,372,036,854,775,808到9,223,372,036,854,775,807的值?

这是一些代码。我想在NSlog self.bufferOffset中显示,这应该是发送的大约几个字节。

        // 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);

以下是一些输出:

  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

1 个答案:

答案 0 :(得分:3)

代码中的

self.bufferOffset是缓冲区中第一个读但尚未写入的字节的偏移量,因此您将始终拥有

 self.bufferOffset <= kSendBufferSize

这(希望)解释了为什么NSLog()输出受32768限制。

self.bufferOffset不是写入的总字节数。

备注:正如其他人已经评论过的那样,%zu格式可以正常使用size_t变量。在64位平台上,size_t是64位无符号整数。例如:

size_t s = 18446744073709551615ULL; // 2^64-1
NSLog(@"%zu", s);
// Output: 18446744073709551615