What this is is an extremely bad way of examining the memory used by a double. In fairness there are no good ways to do this but there are less bad ways.
This way makes assumptions about how memory (on the stack) works and how integers are represented on the platform and it uses C style casts not C++ casts.
A better way (but still not good because generally there is no good way to directly access the memory of another object) is to declare your memory with double type instead of int type so there are no assumptions about how memory works when accessed to store a double and then to access this memory using a char pointer.
Using char over int is better because of the fundamental differences between the 2 types as specified in the standard. You see a platform is free to define it's own representation of an integer in memory which may mean that not all bits in the integer actually go to make up its value, some of the bits may be used for trap values, that means if you point a int pointer at a random piece of memory, say a double (or copy a double into an int) you have have a bit set in one of the trap values and the data may not represent a valid integer on the platform at all.
However char is different, they standard guarantees that all bits of the char must represent a bit in memory that the bits in the char are contiguous bits in memory and that contiguous chars represent contiguous locations in memory, that is an array of char is an exact representation of the underlying memory.
All that gives something like this
-
#include <iostream>
-
#include <iomanip>
-
-
using namespace std;
-
-
int main()
-
{
-
double test = 13.0;
-
-
cout << "Memory bytes making up the value: " << test << endl;
-
-
unsigned char *memptr = reinterpret_cast<unsigned char*>(&test);
-
-
for(size_t ix = 0; ix < sizeof(test); ix++)
-
{
-
cout << setw(2) << setfill('0') << hex << unsigned(memptr[ix]) << " ";
-
}
-
-
cout << endl << endl;
-
-
// To get it as integer values used maths to ensure correct representation in memory
-
unsigned upper = 0;
-
unsigned lower = 0;
-
-
// Note this assumes little endian since I am doing it on a intel processor
-
lower = memptr[0] | (memptr[1] << 8) | (memptr[2] << 16) | (memptr[3] << 24);
-
upper = memptr[4] | (memptr[5] << 8) | (memptr[6] << 16) | (memptr[7] << 24);
-
-
// display the results
-
cout << "The final results are:" << endl;
-
cout << dec << "upper = " << upper << endl;
-
cout << dec << "lower = " << lower << endl;
-
-
return 0;
-
}
-
Note this isn't good, it is just less bad.