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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to create union for word (two bytes) in C++

1 Answer

0 votes
#include <iostream>

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

union Twobytes {
private:
	unsigned short w;      
	unsigned char ch[2];   
public:             
	unsigned short &word() {
		return w;
	}
	unsigned char &lowByte() {
		return ch[0];
	}
	unsigned char &highByte() {
		return ch[1];
	}
};

int main()
{
	Twobytes w;

	w.word() = 0x3210;

	cout << "Word: " << (int)w.word() << endl;
	cout << "lowByte: " << (int)w.lowByte() << endl;
	cout << "highByte: " << (int)w.highByte() << endl;

	return 0;
}


/*
run:

Word: 12816
lowByte: 16
highByte: 50

*/

 



answered May 29, 2018 by avibootz

Related questions

1 answer 137 views
137 views asked May 29, 2018 by avibootz
1 answer 113 views
1 answer 155 views
155 views asked Dec 11, 2020 by avibootz
2 answers 160 views
1 answer 137 views
137 views asked Mar 17, 2018 by avibootz
1 answer 159 views
...