Free, tested & ready to use examples : C++ union example color data file 32 bit int
AnyExample.com
 
Webanyexample.com
 

Example of using union in C++

abstract 
union is a user-defined type that uses same block of memory for every its list member
compatible 
  • Any modern C++ compiler

Union may be useful when it is necessary to work with different representation of same binary data.

For example, you need to store color data as four 8-bit unsigned char numbers. At the same time, you have to store this color data as one 32-bit unsigned integer. Union allows to use both representation(struct with 4 unsigned char and unsigned integer) at the same time, using same block of computer's memory.

The union is declared as:

union union-type-name { union-list } union-variable;
In this form, union-type-name is optional. However, if you want to use union type in several places, it is better to use another way of enum declaration:
union union-type-name { union-list };

//... (and somewhere below)

union union-type-name union-variable;
Of course, in the second case union-type-name cannon be omitted.

Example: declaring union type for color data

source code: C++
 
union u_color {
	// first representation (member of union)
	struct s_color { 
		unsigned char a, b, g, r;
	} uc_color;
 
	// second representation (member of union)
	unsigned int i_color; 
};
?>
 

After declaration, it is possible to use union-type-name as user-defined type.

Following example demonstrates basic union usage. It reads file which contains 32 bit unsigned ints and decodes it to four 8 bit RGBA (Red, Green, Blue, Alpha-Transparency) values.

source code: C++
 
#include <iostream>
#include <stdio.h>
using namespace std;
 
union u_color {
	// first representation (member of union)
	struct s_color { 
		unsigned char a, b, g, r;
	} uc_color;
 
	// second representation (member of union)
	unsigned int i_color; 
};
 
int main(void) {
	FILE *f = fopen("color.dat", "rb");
	if (f == NULL)
		exit(1);
 
	fseek(f, 0, SEEK_END);
	size_t size = ftell(f); 
	// file size in bytes
	fseek(f, 0, SEEK_SET);
	size /= 4;
	// file size in 32bit ints
 
	for(size_t i=0; i<size; i++)
	{
		u_color clr;
		//reading from tile to clr.i_color
		fread(&clr.i_color, sizeof(unsigned int), 1, f);
 
		// printing from clr.uc_color to output stream
		cout << "R=" << int(clr.uc_color.r) << " ";
		cout << "G=" << int(clr.uc_color.g) << " ";
		cout << "B=" << int(clr.uc_color.b) << " ";
		cout << "A=" << int(clr.uc_color.a) << endl;
	}
 
	fclose(f);
}
 



warning 
  • Union most likely will cause cross-CPU (endianess) problems with you application. This is irrelevant if you write programs only for x86 processors
tested by AnyExample.com on 2006-10-07
  • Windows XP :: Microsoft Visual C++ 2003
  • Free BSD 5.2 :: gcc 3.3.3
 


 
© AnyExample 2007
License | Privacy | Contact