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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.