BIT operations:

 

BIT operations:

Terminology:

Bit is set: bit value is 1 at that position.

  1. The & (bitwise AND) takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  
  1. The | (bitwise OR) takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1. 
  1. The ^ (bitwise XOR) takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. 
  1. The << (left shift) takes two numbers, the left shifts the bits of the first operand, and the second operand decides the number of places to shift. Can be used to multiply by 2 power (n) example a<<b means a* 2Power (b).  also a&(1<<n)  will tell whether nth bit is set on a or not.
  1. The >> (right shift) takes two numbers, right shifts the bits of the first operand, and the second operand decides the number of places to shift. Can be used to divide by 2 power (n) example a<<b means a/ 2Power (b). (num>>i)&1 can tell you ith bit from right is set or not, returns 1 if set and 0 if not set, you can do it for n numbers to count how many numbers have ith bit set.
  1. The ~ (bitwise NOT) takes one number and inverts all bits of it.

 

Note: If we perform operations on two ints then it will perform operation on each bits of two numbers and result the output by forming the number using resulting bit sequence after the operation.

Comments

Popular posts from this blog

LeetCode 3Sum

New start Day 2 (1/10/2020) codeforces 492B Vanya and Lantern

Heap (min)