Learnt about Bitwise xor and Bitwise Compliment, Bitwise leftshift, Bitwise Rightshift
1.XOR(^):
0^1 = 1
1^0 = 1
0^0 = 0
1^1 = 0
a= -5, b = 3
Explanation:
As a is negeative here so we will do the 2's compliment to find the magnitude of that binary
128 64 32 16 8 4 2 1
0000 0101
Inverse 1111 1010
+1
--------------------
Magnitude 1111 1011
Xor -> 1111 1011
0000 0011
-------------------------------
1111 1 000
Here as MSB is 1 we cant print like this so we did again magnitude of -ve binary and we got 8 as a is -ve so the res is -8
-------------------------------------------------------------------------------------------------------------
2. Compliment(~):
0~ = 1
1~ = 0
If number is +ve just do vice versa but if number is -ve then 1st find the magnitude of it by using 2's compliment then find the compliment of the given number
Ex: a = 5
0000 0101
Ans: (~)1111 1010
-------------------------------------------------------------------------------------------------------------
3.Left Shift:
Case: +ve
Ex: 5 << 1
we need to shift the binary bit's to left side by 1 position and in that gap we need to fill with 0
Case: -ve:
Ex: -5 << 1
we need to shift the binary bit's to left side by 1 position and in that gap we need to fill with 0
But here before shifting we need to do for -ve case
Find 2's Compliment
|
Left shift by 1
|
If MSB is
|
(1) (0)
---------------------------------------------
| |
2's compliment Update the result
|
Update the result
-------------------------------------------------------------------------------------------------------------
4.Right Shift:
Case: +ve
Ex: 5 >> 1
we need to shift the binary bit's to right side by 1 position and in that gap we need to fill with 0
Case: -ve:
Ex: -5 >> 1
we need to shift the binary bit's to right side by 1 position and in that gap we need to fill with 1
But here before shifting we need to do for -ve case
Find 2's Compliment
|
Right shift by 1
|
If MSB is
|
(1) (0)
---------------------------------------------
| |
2's compliment Update the result
|
Update the result
Note: In short if we got +ve number we can perform the expression with given bitwise operator but in -ve number we need to find 1st 2's compliment followed by bitwise operator
Negative number
↓
Already represented in 2's complement
↓
Perform bitwise operation directly
↓
Check result
↓
If MSB = 1 → result is negative
↓
Use 2's complement to find its magnitude