- We can apply these operators bitwise.
- These operators are applicable only for int and Boolean types.
- By mistake if we are trying to apply for any other type then we will get Error.
- Bitwise operators are;
- & (Bitwise and) ⇒ If both bits are 1 then only result is 1 otherwise result is 0.
- | (Bitwise or) ⇒ If atleast one bit is 1 then result is 1 otherwise result is 0.
- ^ (Bitwise xor) ⇒ If bits are different then only result is 1 otherwise result is 0.
- ~ (Bitwise complement) ⇒ bitwise complement operator i.e. 1 means 0 and 0 means 1 and it complement for total bits.
- << (Bitwise left shift)
- >> (Bitwise right shift)
Example
Python
print(4&5)
print(4|5)
print(4^5)
print(~5)
print(True & False)
Output
PowerShell
4
5
1
-6
False
Example
Python
print(10.5 & 5.6)
Output
PowerShell
TypeError: unsupported operand type(s) for &: 'float' and 'float'
Remark
- The most significant bit acts as sign bit. 0 value represents +ve number where as 1 represents -ve value.
- Positive numbers will be represented directly in the memory where as -ve numbers will be represented indirectly in 2’s complement form.
Operator | Description |
& | If both bits are 1 then only result is 1 otherwise result is 0 |
| | If atleast one bit is 1 then result is 1 otherwise result is 0 |
^ | If bits are different then only result is 1 otherwise result is 0 |
~ | bitwise complement operator i.e. 1 means 0 and 0 means 1 |
>> | Bitwise Left shift Operator |
<< | Bitwise Right shift Operator |
Bitwise Complement Operator (~)
- We have to apply complement for total bits.
Example
Python
print(~5)
Output
PowerShell
-6
Shift Operators
There are two types of shift operators.
- Left shift operator (<<)
- Right shift operator (>>)
<< Left shift operator
- Shift the digits from right to left.
- After shifting the empty cells we have to fill with zero.
Example
Python
num1 = 10
print(bin(num1))
num1 = num1<<2
print(bin(num1))
Output
PowerShell
'0b1010'
'0b101000'
>>Right Shift operator
- Shift the digits from left to right.
- After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)
Example
Python
num1 = 10
print(bin(num1))
num1 = num1>>2
print(bin(num1))
Output
PowerShell
'0b1010'
'0b10'
Remark
- We can apply bitwise operators for Boolean types also.
Python
print(True & False)
print(True | False)
print(True ^ False)
print(~True)
print(True>>2)
Output
PowerShell
False
True
True
-2
0
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!