I'm trying to create a double
by appending the binary representations of two int
s. This is what I have now:
int i = arc4random();
*(&i+1) = arc4random();
double d = *(double*)&i;
I hoped the double
pointer would also use the value in the &i+1
address, and this is indeed the case. When I print the binary representations of i
and *(&i+1)
and compare them to the binary representation of d
, d is composed by appending *(&i+1)
and i
. So *(&i+1)
comes first?! Why is this the case?
EDIT: also take a look at the answers of Juan Catalan and Mark Segal to know what's the right way of doing what I did using unions.
Use a union
instead. You still could generate a NaN But won't have memory management issues.
This is the whole purpose of a union
, share a memory block among several different types.
Make sure in your architecture sizeof(double)
is equal to twice sizeof(int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With