bitmask c 2b 2b

Solutions on MaxInterview for bitmask c 2b 2b by the best coders in the world

showing results for - "bitmask c 2b 2b"
Vicente
29 May 2018
1Bitwise Operator
2//if both are true then true else false
3&
4//if both are false then false else true
5|
6//changes true into false and vice-versa
7~
8//returns true if exactly one is true else false
9//checks if both are different
10^
11//a<<b multiply a with 2 , b times
12<<
13//a>>b divide a with 2 ,  b times
14>>
15-------------------------------------------------
16check whether a numbe is a power of 2
17i.e if it comes in the format 2**n
18int x;
19cin >>x;
20cout<<~(x&(x-1));
21-------------------------------------------------
22count no of ones in the binary representation of th given number
23int count = 1;
24while(n!=0){
25    count++;
26    n = n&(n-1);
27}
28-------------------------------------------------
29check whether the i'th bit is set or not i.e 1
30for the binary of number n
31if(n & (1<<i) == true){
32    cout<<"Yes it is a bit"
33}
34-------------------------------------------------
35
Philippe
07 Jul 2017
1- Set ith bit:    x|(1<<i)
2   1100 1100
3|  0001 0000    (1<<i)
4  -----------
5   1101 1100  
6  
7- Get ith bit:    (x&(1<<i) != 0)
8    0010 1100
9&   0010 0000   (1<<i)
10  ------------
11    0010 0000   (is not zero)
12
13- Clear ith bit:   x&(~(1<<i))
14                      ~ : inverts
15   0011 0110
16&  1101 1111   ~(1<<i)
17  -----------
18   0001 0110