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() { ...

C Program to Extract n Bits from a Given Bit Position

🧠 C Program to Extract n Bits from a Given Bit Position

#include <stdio.h>

int main() {
    int num, pos, n;

    // Input number, position, and number of bits
    printf("Enter the number: ");
    scanf("%d", &num);

    printf("Enter the starting bit position (0-based): ");
    scanf("%d", &pos);

    printf("Enter the number of bits to extract: ");
    scanf("%d", &n);

    // Step 1: Right shift to bring desired bits to the end
    int shifted = num >> (pos - n + 1);

    // Step 2: Mask with n 1's => (1 << n) - 1
    int mask = (1 << n) - 1;

    // Step 3: AND operation to get only those n bits
    int result = shifted & mask;

    printf("Extracted %d bits from position %d = %d (binary)\n", n, pos, result);

    return 0;
}
  

πŸ“ Explanation:

This C program extracts n bits from a number starting at a specified bit position pos (0-based from LSB).

  • num >> (pos - n + 1) shifts the desired bits to the end.
  • (1 << n) - 1 creates a bitmask of n 1's.
  • & operation filters out only the required bits.

πŸ’‘ Sample Output:

Enter the number: 182
Enter the starting bit position (0-based): 7
Enter the number of bits to extract: 3
Extracted 3 bits from position 7 = 2 (binary)
  

πŸ” Keywords:

bitwise extraction C, extract bits from number in C, shift mask AND example, C programming bit manipulation

πŸ” Extract n Bits from a Number at a Given Position

Example:

  • Number: 202
  • Binary: 11001010
  • Position: 6 (counting from LSB = 0)
  • Bits to extract (n): 3

🧠 Step-by-Step Visual Diagram:

Bit Index:    7   6   5   4   3   2   1   0
Binary:       1   1   0   0   1   0   1   0
Extracting:       ↑   ↑   ↑
                 pos=6 (3 bits: 6,5,4)

Selected Bits:    1   0   0  → Binary = 4
  

πŸ“Œ Explanation:

  1. Convert the number to binary: 202 → 11001010
  2. Start from position 6, extract 3 bits → positions 6, 5, and 4
  3. Bits at those positions = 1 0 0
  4. Binary 100 = Decimal 4

✅ Final Output: 4

Comments

Popular Posts

πŸŒ™