C program to extract individual bytes from an unsigned int using union

In this program, we are going to extract individual bytes from an unsigned integer variable using C programming language union.

As we discussed in C - Union tutorial that union takes memory for largest data type element and other variables share that memory.

Thus, if we assign a value to an integer variable inside union a character array of 4 bytes will use the same bytes.

In this example, there will be two variables a as unsigned int and s as unsigned char array. We will assign the value to unsigned int variable and unsigned char array will point the same value.

C union program to extract individual bytes from an unsigned int


union tagname
	unsigned int a;
	unsigned char s[4];

union tagname object;

int main()
	char i; //for loop counter

	//assign an integer number

	printf("Integer number: %ld, hex: %X\n",object.a,object.a);

	printf("Indivisual bytes: ");
		printf("%02X ",object.s[i]);

	return 0;


Integer number: 2864434397, hex: AABBCCDD
Indivisual bytes: AA BB CC DD

C Structure & Union Programs »



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.