Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Liquid Web Managed Dedicated Server: RAID 1 SSD with 16GB of RAM minimum! 24/7 On-Site Heroic Support! Industry-Leading SLA!

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Liquid Web Cloud VPS Hosting

8,365 questions

11,625 answers

573 users

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

1 Answer

0 votes
#include <iostream>

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

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

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

void bits::print_in_byts(int in_one_line)
{
	for (int j = sizeof(int) - 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 ibits(13);

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

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

	return 0;
}



/*
run:

Bit in byte 3: 00000000
Bit in byte 2: 00000000
Bit in byte 1: 00000000
Bit in byte 0: 00001101

00000000000000000000000000001101

*/

 




answered Mar 16 by avibootz
...