开发者

Random bit double questions

I saw the following line in GTMHTTPFetcher.m of gtm-http-request:

// set min interval to a random value between 1.0 and 2.0 seconds
minRetryInterval_ = 1.0 + ((double)(arc4random() & 0x0FFF开发者_如何学PythonF) / (double) 0x0FFFF);
  1. Why are both operands of the division operator being cast to doubles?

  2. What does the & 0x0FFFF do?

  3. Does this work independent of the system's endianness?

  4. How can we be sure that 0x0FFFF is always larger than arc4random() & 0x0FFFF? What if the system uses two's compliment?


  1. Both operands of the division operator are being cast to doubles because minRetryInterval_ is an NSTimeInterval, which is of typedef double. Perhaps, it might make more sense to cast them both to NSTimeIntervals instead.

  2. The & 0x0FFFF zeros out all but the right-most 16 bits of the random u_int32_t, i.e., unsigned int, generated by arc4random().

  3. Yes, this should work independent of the system's endianness because the denominator, 0x0FFFF, is the largest possible 16 bit double, and so, the quotient will always be less than or equal to 1.

  4. The most significant bit of a double is a sign bit. In this case, both sign bits are 0, so we can be sure the quotient will be positive. Also, according to the specification for double, 0x0FFFF is greater in magnitude than 0x0FFFE, for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜