Bitwise operators and algorithms.
Hey everyone, this is my first time blogging about my learnings of Data structures and algorithms and this was an interesting one. Huge shoutout to Kunal Kushwaha for being as rigorous and exceptional as ever.
To get things going let us understand what bitwise operators are:
They can only be applied to integer data types i.e., you can't use them on floats or double.
Bits numbering in variable start from right to left.
There are mainly these operators which are extensively used:
the AND operator (denoted by &)
the OR operator (denoted by |)
the exclusive OR or Zawr as Kunal says it :P (denoted by ^)
and the NOT operator (denoted by ~)
The bitwise left shift (denoted by <<)
The bitwise right shift (denoted by >>)
If we take the ith bit of say, x is 0 and the ith bit of say y is also 0. Then the resulting answer of ith bit of z = x & y would result in 0.
Similarly, for the same set of inputs, the value for x | y would also result in 0. And so would the answer for x ^ y. However, for z = ~x would here give 1 as the value of x = 0.
ith bit of x | ith bit of NOT z = x | ith bit of y | ith bit of AND z | ith bit of OR z | ith bit of XOR Z |
0 | 1 | 0 | 0 | 0 | 0 |
0 | 1 | 1 | 0 | 1 | 1 |
1 | 0 | 0 | 0 | 1 | 1 |
1 | 0 | 1 | 1 | 1 | 0 |
Few additional properties:
If you & 1 any number, the digits remain the same i.e, a & 1 = a.
If you a^1 the result would be the complement of a. For example. 1^0 = 0 and 0^1=1.
a^a = 0 and a^0 = a
For a left shift, a << 1 = 2a. That is if you left shift a number by 1 its value doubles in size.
For a right shift a >> b = a/2b. Pretty self-explanatory.
Alright, so this is it as far as the fundamentals about bitwise operators are concerned.
Peace. Be back soon!
Kevin.