Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 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, 2018 by avibootz

Related questions

1 answer 195 views
1 answer 224 views
1 answer 185 views
185 views asked Aug 29, 2016 by avibootz
2 answers 338 views
1 answer 223 views
...