Search code examples
cbinarydoublebit-manipulationarc4random

Create double by appending binary representations of two ints


I'm trying to create a double by appending the binary representations of two ints. 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.


Solution

  • 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?

    the actual ordering of the bytes depends upon the 'Endian-ness' of the underlying hardware architecture.

    with little Endian architecture:

    1) the lowest address byte contains the least significant 8 bits of the total variable  
    2) the highest address byte contains the most significant 8 bits of the total variable.