2. Remaining Bitwise Operators #

Created Sunday 28 June 2020

Note:

  1. These are different from &&, || and ! which are meant for booleans only.
  2. All 4 ops are commutative, associative and distributive.

Types of gate bitwise ops:

  1. AND ⇒ &

  1. Check if bit is set/unset, inter-alia check if even or odd(no shifts required)

    x & 1 = x; // check if a bit is set/unset
    
  2. OR ⇒ |

  1. Check if bit is set/unset

    x | 0 = x; // x is a bit
    
  2. NOT ⇒ ~ ⇒ unary operator

  1. XOR ⇒ ^ (The most useful)

  1. Works as binary switch for any bit
    x ^ 1 = ~x; // same as ~x
    

  1. Predict The Output
#include<iostream>
using namespace std;
int main(){
	if(~0 == 1) {
		cout << "yes";
	}
	else {
		cout << "no";
	}
}
  1. yes
  2. no
  3. Compile time error
  4. Undefined

Answer: B. ~0 = -(0+1) = -1 and not 1. Bitwise. not !

  1. Predict The Output
#include <iostream>
using namespace std;
int main(){
    int y = 0;
    if(1 | (y = 1)) {
        cout << "y is " << y;
    }
    else {
        cout << y;
    }
}
  1. y is 0
  2. y is 1
  3. 1
  4. 0

Answer: B. Because in C++ an assigment has a value equal to the rvalue. So y==1 is the same as 1. This is allowed only in low level languages.

  1. Predict The Output
#include <iostream>
using namespace std;

int main(){
   int y = 1;
   if(y & (y = 2))
      cout << "true";
   else
   cout << "false";
}

Answer: true Reason: 32 is the answer in the assigment because no buffer is created. in 2 & 3 ⇒ 2 and 3 both have different buffer variables. in (y=2) & (y=3) ⇒ there are no buffer variables created, this is how assignment operator works. So is is like 3 & 3. in (y=3) & (y=2) ⇒ 2 & 2