Skip to main content

Featured

C Pattern Programs: Square Number and Alphabet Patterns Explained

πŸ”· Square Star Pattern πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { printf("* ");//keep"* " } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Column-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = num; i >= 1; i--) { for(int j = num; j >= 1; j--) { printf("%c ", j + 64);//%c for Character and 64 will be ASIIC VALUE } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Row-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; ...

C Program: Union and Nibble Sum of a Hexadecimal Number

C Program: Union and Nibble Sum

πŸ”· C Program: Union and Nibble Sum of a Hexadecimal Number

#include <stdio.h>

union byteunion
{
    unsigned int full_word;
    unsigned char bytes[4];
};

int main( )
{
    union byteunion data;
    scanf("%x", &data.full_word);

    int upper_sum = 0, lower_sum = 0;

    printf("\nBytes: ");
    for (int i = 3; i >= 0; i--)
    {
        printf("0x%02X", data.bytes[i]);
        if (i != 0)
            printf(", ");
    }

    for (int i = 0; i < 4; i++)
    {
        int byte = data.bytes[i];
        int upper = byte / 16;
        int lower = byte % 16;
        upper_sum += upper;
        lower_sum += lower;
    }

    printf("\nUpper nibble addition: 0x%02x", upper_sum);
    printf("\nLower nibble addition: 0x%02X\n", lower_sum);
}
  

πŸ“˜ Explanation:

This program demonstrates how to use a union in C to access individual bytes of a 32-bit hexadecimal input.

πŸ”Ή A union is used to share memory between an unsigned int and an array of 4 bytes.
πŸ”Ή The user inputs a 32-bit hexadecimal number.
πŸ”Ή The program prints all 4 bytes from most significant to least significant.
πŸ”Ή Each byte is split into upper and lower 4-bit nibbles.
πŸ”Ή It then calculates and displays the sum of upper and lower nibbles separately in hexadecimal format.

πŸ” Sample Output:

Input:
12345678

Output:
Bytes: 0x12, 0x34, 0x56, 0x78
Upper nibble addition: 0x15
Lower nibble addition: 0x14
    

🏷️ Keywords:

C union example, hexadecimal byte access, nibble sum, bitwise manipulation, memory sharing in C, byte array, 32-bit hex analysis

Comments

Popular Posts

πŸŒ™