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() & 0x0FFFF) / (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 than arc4random() & 0x0FFFF
? What if the system uses two's compliment?
Both operands of the division operator are being cast to double
s because minRetryInterval_
is an NSTimeInterval
, which is of typedef double
. Perhaps, it might make more sense to cast them both to NSTimeInterval
s instead.
The & 0x0FFFF
zeros out all but the right-most 16 bits of the random u_int32_t
, i.e., unsigned int
, generated by arc4random()
.
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.
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.