Commit 52961e5e authored by BRENO RILHO LEMOS's avatar BRENO RILHO LEMOS

Using unions and working with bits

parent d53cf0e2
#include <iostream>
using namespace std;
union bits { // In UNIONS and STRUCTURES, all members are public until [ private: ] is specified.
bits(double n); // Constructor
void show_bits();
double d;
unsigned char c[sizeof(double)];
};
bits::bits(double n) {
d = n;
}
void bits::show_bits() {
cout << "Number is " << d << "\n";
int i, j;
for(j = sizeof(double) - 1 /* = 8-1 = 7 */; j>=0; j--) {
cout << "Bit pattern in byte " << j << ": ";
for(i=128 /* in binnary: 1000 0000 */; i; i = i>>1 /* right shifts => moves digit 1 to the right each execution */)
if(i & c[j]) cout << "1"; // returns 1 if that bit of c[j] is 1
else cout << "0";
cout << "\n";
}
// Essentially, the program creates an empty char array c whose elements contain the same bit pattern as each byte of double d.
//That happens because unions have all their members share the same memory location.
}
int main() {
bits breno(15.0); // Apparently, digits are stored "backwards"
bits pedroia(1991.829);
breno.show_bits();
cout << "\n";
pedroia.show_bits();
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment