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 114 views
114 views asked May 29, 2018 by avibootz
1 answer 90 views
1 answer 120 views
120 views asked Dec 11, 2020 by avibootz
2 answers 141 views
1 answer 120 views
120 views asked Mar 17, 2018 by avibootz
1 answer 147 views
...