How to use union to define a class than print bits of a double number in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

union bits {
	double n;
	bits(double number);
	void print_in_byts(int in_one_line);
	unsigned char arr[sizeof(double)];
};

bits::bits(double number)
{
	n = number;
}

void bits::print_in_byts(int in_one_line)
{
	for (int j = sizeof(double) - 1; j >= 0; j--) {
		if (!in_one_line) cout << "Bit in byte " << j << ": ";
		for (int i = 128; i; i >>= 1)
			if (i & arr[j]) 
				cout << "1";
			else 
				cout << "0";
			if (!in_one_line) cout << endl;
	}
}

int main()
{
	bits dbits(3.14);

	dbits.print_in_byts(0);
	cout << endl;

	dbits.print_in_byts(1);
	cout << endl;

	return 0;
}


/*
run:

Bit in byte 7: 01000000
Bit in byte 6: 00001001
Bit in byte 5: 00011110
Bit in byte 4: 10111000
Bit in byte 3: 01010001
Bit in byte 2: 11101011
Bit in byte 1: 10000101
Bit in byte 0: 00011111

0100000000001001000111101011100001010001111010111000010100011111

*/

 



answered Mar 16, 2018 by avibootz

Related questions

1 answer 155 views
1 answer 158 views
158 views asked Aug 29, 2016 by avibootz
2 answers 297 views
1 answer 189 views
1 answer 190 views
...