Pages

Saturday, May 3, 2025

Q. Clear range from ith to jth bit (Bit Manipulation)

 #include <iostream>

using namespace std;

// goal- to clear from left and right bit of number

int main()

{

    int i = 1, j = 3;

    int num = 31; // 0b01111


    int left = ~0 << (j + 1);       // Clears bits j and above

    int right = (1 << i) - 1;       // Sets bits below i

    int bitMask = left | right;     // Clears bits from i to j

    int result = num & bitMask;     // Apply the mask


    cout << "Bitmask: " << bitMask << endl;

    cout << "Result: " << result << endl;


    return 0;

}


No comments:

Post a Comment

Binary Search in a Sorted Array in C++

 #include <iostream> using namespace std; int binarySearch(int arr[], int key, int n) {     int si = 0;      int ei = n-1;          wh...