Updated 30 March 2022
Bitwise operators are used in low-level programming. It performs operations at the individual bit level. It is also used in encoding and decoding data for custom protocol communication.
List of Bitwise operators:
First is Bitwise AND Operator.
The second is Bitwise OR Operator.
The third is Bitwise NOT Operator.
Fourth is Bitwise XOR Operator.
And last is Bitwise Shift Left and Shift Right Operator.
1 Bitwise AND Operator:- This operator returns 1 only when both the operand are 1 else it returns 0. Its symbol is “&”.
Example.
1 2 3 |
let firstNumber = 40 let secondNumber = 28 print(firstNumber&secondNumber) // 8 |
In the above example, the binary of 40 is “00101000” and the binary of 28 is “00011100”. So when we perform Bitwise AND operations then the result will be “00001000” which is “8” in decimal.
2 Bitwise OR Operator:- This operator returns 1 when either one operand is 1 else it returns 0. Its symbol is “|”.
Example
1 2 3 |
let firstNumber = 40 let secondNumber = 28 print(firstNumber|secondNumber) // 60 |
Similarly, like the Bitwise And operator example, when we perform the Bitwise OR operation on “00101000”, “00011100” the result will be “00111100” which is 60 in decimal.
3 Bitwise NOT Operator:- This operator inverts the bit. Its symbol is “~”.
Example
1 2 3 |
let firstNumber = 40 print(~firstNumber)// -41 |
When we perform Bitwise Not operation on 40 then it will be -40( (-40+1) ).
4 Bitwise XOR Operator:- It returns 1 only if one of the operands is 1 else 0. Its symbol is “^”.
Example
1 2 3 |
let firstNumber = 40 let secondNumber = 28 print(firstNumber^secondNumber) //52 |
5 Bitwise Shift Left and Shift Right Operator:- The Bitwise shift Left operators shifts the bit to the left side by a specific number of bits. Its symbol is “<<“. whereas The Bitwise shift Right operators shift the bit to the Right side by a specific number of bits. Its symbol is “>>”.
Example
1 2 3 4 5 6 7 8 9 |
let firstNumber = 40 //Bitwise Shift Left Operator print(firstNumber<<1) // 80 print(firstNumber<<2) // 160 //Bitwise Shift Right Operator print(firstNumber>>1) // 20 print(firstNumber>>2) // 10 |
Thanks for reading this blog.
You can also check other blogs from here. If you have any issues, queries, or suggestions then you can leave your issues/queries/suggestions in the comment section.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.