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; ...

Swap Nibbles of 8-bit Number in C

Swap Nibbles of 8-bit Number in C

✅ Swap Nibbles of 8-bit Number in C

#include <stdio.h>  // Header file for input/output functions

// Macro to swap the nibbles (4-bit groups) of an 8-bit number
// (x & 0x0F) extracts the lower nibble (last 4 bits)
// (x & 0xF0) extracts the upper nibble (first 4 bits)
// << 4 shifts lower nibble to upper position
// >> 4 shifts upper nibble to lower position
// The OR '|' combines both into the swapped result
#define SWAP_NIBBLES(x)  (((x & 0x0F) << 4) | ((x & 0xF0) >> 4))

int main() {
    unsigned char num;  // Declare an 8-bit unsigned variable

    printf("Enter an 8-bit number (0-255): ");  // Prompt user for input
    scanf("%hhu", &num);  // Read input as unsigned char using %hhu format specifier

    // Call the macro to swap the nibbles and store result in 'swapped'
    unsigned char swapped = SWAP_NIBBLES(num);

    // Print the result after swapping nibbles
    printf("After swapping nibbles: %u\n", swapped);

    return 0;  // Return 0 to indicate successful execution
}
  

πŸ“˜ Explanation:

This program demonstrates how to swap the two 4-bit nibbles of an 8-bit number using a macro. A macro named SWAP_NIBBLES is defined to isolate the lower and upper nibbles using bitwise AND with 0x0F and 0xF0 respectively. The lower nibble is shifted left by 4 bits and the upper nibble is shifted right by 4 bits, then both are combined using the bitwise OR | operator.

The user inputs an 8-bit number (from 0 to 255), and the program displays the result after nibble swapping. This technique is useful in embedded systems, low-level data processing, and binary manipulations.

🧾 Sample Output:

Enter an 8-bit number (0-255): 100
After swapping nibbles: 70
  

πŸ”‘ Keywords:

Swap Nibbles in C, Bitwise Operations, C Macros, 8-bit Manipulation, Embedded C, Nibble Swapping, Low-level C Programming

πŸ“Œ Hashtags:

#CProgramming #BitwiseOperators #MacrosInC #SwapNibbles #EmbeddedC #LowLevelCoding

Comments

Popular Posts

πŸŒ™