Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

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

๐ŸŒ™