Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
Rugen Heidbuchel Avatar asked Mar 15 '23 21:03

Rugen Heidbuchel


1 Answers

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)

like image 140
Juan Catalan Avatar answered Apr 26 '23 17:04

Juan Catalan