Learning Python - 4th Day (Morning - 1)
Watched this tutorial: Click here
I have learnt about bitwise operators.
They are:
- ~ (Complement operator): The work this operator does is to make the binary format of a number opposite.
I know this seems to be complicated if you haven't still find it in your books. But Let me make it simple.
Let's have an example:
Python:
Input: ~32
Output: -33
I recommend you to watch this tutorial to learn how complement operators process a number. - & (Bitwise And) : Works similarly like AND gate.
If I take multiple numbers and try to apply (&) operator between them the system will give an output of (If both numbers are 1 then output is 1 but if both numbers are different then output will be smaller one.) Let me make it simple: - >>> 1&0
- 0
- >>> 1&1
- 1
- >>> 0&0
- 0
- >>> 12&13
- 12
- >>> 12&12
- 12
- >>> 13&12
- 12
- >>> 13&13
- 13
- >>> 1&0&1
- 0
- | (Bitwise Or) : Works similarly like (or) function but as an operator. If I put 12 or 13 as and input I am expecting to get one of the two numbers as output.
- ^ (Bitwise XOR): This operator is simple. Let me explain:
----------------------------------------------
|| Input 1 || Input2 || XOR Output ||
||------------||-----------||------------------||
|| 0 || 1 || 1 ||
-----------------------------------------------
|| 1 || 0 || 1 ||
-----------------------------------------------
|| 0 || 0 || 0 ||
-----------------------------------------------
|| 1 || 1 || 0 ||
-----------------------------------------------
Shortcut: Whenever both inputs are different, you get (1) - << (Left shift) : Shift the binary format of a number to left.
Example:
Input: 10<<3
Output: 80
How this works?
Ans: First convert the Input you gave to binary format.
In my case it is (10)
Binary format of (10) is 1010
Same as: 1010.0000.....infinity
Now you need to take a certain number of zeros from the right side of this binary format
push them to left. In my case I have selected (3). So I need to shift 3 zeros from right to left.
So to corresponding output will be: 1010000.0.....infinity
Now if I convert the output binary to decimal. It will be 80 - >> (Right Shift): Similar to left shift, but this time you need to push numbers from left to right.
Example:
Input: 10>>3
Output: 1
Binary of 10 is : 1010.0000.... infinity
Right shift 3 numbers from it: 0001.01000....infinity
Clean binary : 0001 or the decimal of this will be 1
Special thanks to Navin Reddy sir for teaching me these awesome courses for free!
Learn more about bitwise operators here.
Comments
Post a Comment