Expand|Select|Wrap|Line Numbers
- #include<iostream>
- #include<iomanip>
- #include <bitset>
- #include <limits>
- using namespace std;
- union
- {
- double d;
- char c[sizeof(double)];
- } conv;
- int main()
- {
- // int to float can be done has *(reinterpret_cast<float *>(&intValue));
- int i = 3;
- float f = 4.34;
- f = *(reinterpret_cast<float *>(&i));
- cout << f << endl;
- cout << static_cast<int>(f) << endl;
- // TO STORE VALUES
- //I. double (8 bytes) conversion to a float (4 bytes)
- double n = 3221.12332;
- long n2 = *(reinterpret_cast<long*>(&n));
- long n3 = *(reinterpret_cast<long*>(&n) + 1);
- // DOES NOT WORK
- //II. using unions to get the bit representation of a double
- conv.d = 32;
- // print out double in hex
- for (int i =0; i < sizeof(double); ++i)
- cout << hex << setfill('0') << setw(2) << conv.c[i];
- cout << endl;
- // DOES NOT WORK
- //III. any object can be considered as a sequence of unsigned chars
- double d = 999;
- unsigned char *p=reinterpret_cast<unsigned char *>(&d);
- for(unsigned i=0; i<sizeof(d); ++i)
- cout<<static_cast<unsigned>(p[i])<<" ";
- cout<<endl;
- //IV. DONT KNOW IF IT WORKS
- double d1 = 1000;
- unsigned char *p1=reinterpret_cast<unsigned char *>(&d1);
- // There are systems where 1 byte is more than 8 bits
- bitset<numeric_limits<unsigned char>::digits> byte;
- for(unsigned i=0; i<sizeof(d1); ++i)
- {
- byte = p1[i];
- for(unsigned j=0; j<byte.size(); ++j)
- cout << byte[j];
- }
- // how do we convert to an int and see the same value as that of double
- unsigned long long int x;
- x = *(reinterpret_cast<int *>(&d1));
- cout << "int x: " << x << endl;
- cout<<endl;
- system("pause");
- return 0;
- }