I am currently teaching myself c++ and learning all I can about memory. I found out that you can use a char pointer to copy the bit pattern of an int for example and store it in memory with casting:
#include <iostream>
using namespace std;
int main()
{
int x = 20;
char* cp = new char[sizeof(int)];
cp[0] = *((char*)&x);
cp[1] = *((char*)&x+1);
cp[2] = *((char*)&x+2);
cp[3] = *((char*)&x+3);
std::cout << (int)*cp; // returns 20;
return 0;
}
the code above works, when I cast cp to a int so the compiler reads 4 bytes at a time, I get the correct number which is 20.
However changing it to a float:
#include <iostream>
using namespace std;
int main()
{
float x = 20;
char* cp = new char[sizeof(float)];
cp[0] = *((char*)&x);
cp[1] = *((char*)&x+1);
cp[2] = *((char*)&x+2);
cp[3] = *((char*)&x+3);
std::cout << (float)*cp; // returns 0.
return 0;
}
returns 0. Now I am a bit confused here. If I am copying every single byte, why is it still giving me a 0? If someone could help me out understanding this it would be very awesome.