ADVERTISEMENT
ADVERTISEMENT

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

#include<stdio.h>

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

union tagname object;

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

	//assign an integer number
	object.a=0xAABBCCDD;

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

	printf("Indivisual bytes: ");
	for(i=3;i>=0;i--)
		printf("%02X ",object.s[i]);

	printf("\n");
	return 0;
}

Output

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

C Structure & Union Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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

© https://www.includehelp.com some rights reserved.