C++/Data Type/Union
Anonymous Unions
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
union {
long l;
double d;
char s[4];
} ;
l = 100000;
cout << l << " ";
d = 123.2342;
cout << d << " ";
strcpy(s, "hi");
cout << s;
return 0;
}
Defining and using union WordByte
#include <iostream>
using namespace std;
union WordByte
{
private:
unsigned short w; // 16 bits
unsigned char b[2]; // Two bytes: b[0], b[1]
public: // Word- and byte-access:
unsigned short& word() {
return w;
}
unsigned char& lowByte() {
return b[0];
}
unsigned char& highByte(){
return b[1];
}
};
int main()
{
WordByte wb;
wb.word() = 256;
cout << "\nWord: " << (int)wb.word();
cout << "\nLow-byte: " << (int)wb.lowByte()
<< "\nHigh-byte: " << (int)wb.highByte()
<< endl;
return 0;
}
Use union to swap bytes
#include <iostream>
using namespace std;
union UnionSwapbytes {
unsigned char c[2];
unsigned i;
UnionSwapbytes(unsigned x);
void swp();
};
UnionSwapbytes::UnionSwapbytes(unsigned x)
{
i = x;
}
void UnionSwapbytes::swp()
{
unsigned char temp;
temp = c[0];
c[0] = c[1];
c[1] = temp;
}
int main()
{
UnionSwapbytes ob(1);
ob.swp();
cout << ob.i;
return 0;
}