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);
Why are both operands of the division operator being cast to
double
s?What does the
& 0x0FFFF
do?Does this work independent of the system's endianness?
How can we be sure that
0x0FFFF
is always larger thanarc4random() & 0x0FFFF
? What if the system uses two's compliment?
Both operands of the division operator are being cast to
double
s becauseminRetryInterval_
is anNSTimeInterval
, which is oftypedef double
. Perhaps, it might make more sense to cast them both toNSTimeInterval
s instead.The
& 0x0FFFF
zeros out all but the right-most 16 bits of the randomu_int32_t
, i.e.,unsigned int
, generated byarc4random()
.Yes, this should work independent of the system's endianness because the denominator,
0x0FFFF
, is the largest possible 16 bitdouble
, and so, the quotient will always be less than or equal to 1.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 fordouble
,0x0FFFF
is greater in magnitude than0x0FFFE
, for example.
精彩评论