Skip to main content

Featured

Mastering Hollow Square Patterns in C: Stars, Numbers, Alphabets & Binary

πŸ”’ C Program to Print Hollow Continuous Number Square πŸ“„ Source Code: #include <stdio.h> int main() { int num, k = 0; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(i == 1 || i == num || j == 1 || j == num) { // k increments sequentially only along the borders printf("%d ", k++); } else { printf(" "); } } printf("\n"); } return 0; } πŸ“‹ Copy Code πŸ’» Expected Output (Input: 5): Enter the number: 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 πŸ”’ C Program to Print Standard Hollow Binary Row Square πŸ“„ Source Code (Fixed Specifier): #include <stdio.h> int main() { ...

Set, Clear, Toggle nth Bit in C

Set, Clear, Toggle nth Bit in C

✅ Set, Clear, and Toggle nth Bit in C

#include <stdio.h>

// Function to set the nth bit (make it 1)
int setBit(int num, int n) {
    return num | (1 << n);
}

// Function to clear the nth bit (make it 0)
int clearBit(int num, int n) {
    return num & ~(1 << n);
}

// Function to toggle the nth bit (flip its value)
int toggleBit(int num, int n) {
    return num ^ (1 << n);
}

int main() {
    int num, n;

    printf("Enter a number: ");
    scanf("%d", &num);

    printf("Enter the bit position to manipulate (0-indexed): ");
    scanf("%d", &n);

    printf("\nOriginal number in binary: ");
    for (int i = 31; i >= 0; i--) {
        printf("%d", (num >> i) & 1);
    }

    printf("\n\nAfter setting %dth bit: %d", n, setBit(num, n));
    printf("\nAfter clearing %dth bit: %d", n, clearBit(num, n));
    printf("\nAfter toggling %dth bit: %d", n, toggleBit(num, n));

    printf("\n");

    return 0;
}
  

πŸ“˜ Explanation:

This program demonstrates bit manipulation in C using bitwise operators. The user provides an integer and a bit position (0-indexed). The program then performs:

  • Set Operation: Uses bitwise OR to ensure the nth bit is 1.
  • Clear Operation: Uses bitwise AND with complement to make the nth bit 0.
  • Toggle Operation: Uses XOR to flip the value of the nth bit.
It also prints the binary representation of the original number using bit shifting.

🧾 Sample Output:

Enter a number: 10
Enter the bit position to manipulate (0-indexed): 1

Original number in binary: 00000000000000000000000000001010

After setting 1th bit: 10
After clearing 1th bit: 8
After toggling 1th bit: 8
  

πŸ”‘ Keywords:

Bit manipulation in C, set bit operation, clear bit mask, toggle bit using XOR, left shift, binary number handling, C programming, low-level bit logic

πŸ“Œ Hashtags:

#CProgramming #BitManipulation #SetBit #ClearBit #ToggleBit #BinaryInC #CForBeginners #BitwiseOperations

Comments

Popular Posts

πŸŒ™