bitmask c++

Bitwise Operator
//if both are true then true else false
&
//if both are false then false else true
|
//changes true into false and vice-versa
~
//returns true if exactly one is true else false
//checks if both are different
^
//a<<b multiply a with 2 , b times
<<
//a>>b divide a with 2 ,  b times
>>
-------------------------------------------------
check whether a numbe is a power of 2
i.e if it comes in the format 2**n
int x;
cin >>x;
cout<<~(x&(x-1));
-------------------------------------------------
count no of ones in the binary representation of th given number
int count = 1;
while(n!=0){
    count++;
    n = n&(n-1);
}
-------------------------------------------------
check whether the i'th bit is set or not i.e 1
for the binary of number n
if(n & (1<<i) == true){
    cout<<"Yes it is a bit"
}
-------------------------------------------------

5
3
Awgiedawgie 440215 points

                                    - Set ith bit:    x|(1&lt;&lt;i)
   1100 1100
|  0001 0000    (1&lt;&lt;i)
  -----------
   1101 1100  
  
- Get ith bit:    (x&amp;(1&lt;&lt;i) != 0)
    0010 1100
&amp;   0010 0000   (1&lt;&lt;i)
  ------------
    0010 0000   (is not zero)

- Clear ith bit:   x&amp;(~(1&lt;&lt;i))
                      ~ : inverts
   0011 0110
&amp;  1101 1111   ~(1&lt;&lt;i)
  -----------
   0001 0110

5 (3 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source