C Tutorial/Operator/Bitwise Operator
Содержание
A special feature of the >> and
<source lang="cpp">#include <stdio.h> int main(){
int x, y = 6; x = y >> 1; printf("%d",x); x = y/2; printf("%d",x);
}</source>
Bitwise and: c1 & c2
<source lang="cpp"># include<stdio.h> main() {
char c1 = 4,c2 = 6,c3 = 3; c3 = c1 & c2; printf("\n Bitwise AND i.e. c1 & c2 = %d",c3);
}</source>
Bitwise operator
There are six bit operators:
- bitwise AND(&)
- bitwise OR(|)
- bitwise XOR(^)
- bitwise complement(~)
- left shift(<<)
- right shift(>>)
<source lang="cpp"># include<stdio.h>
main()
{
char c1 = 1,c2 = 2,c3 = 3; c3 = c1 & c2; printf("\n Bitwise AND i.e. c1 & c2 = %c",c3); c3 = c1 | c2; printf("\n Bitwise OR i.e. c1 | c2 = %c",c3); c3 = c1 ^ c2; printf("\n Bitwise XOR i.e. c1 ^ c2 = %c",c3); c3 = ~c1; printf("\n ones complement of c1 = %c",c3); c3 = c1<<2; printf("\n left shift by 2 bits c1 << 2 = %c",c3); c3 = c1>>2; printf("\n right shift by 2 bits c1 >> 2 = %c",c3);
}</source>
Bitwise AND i.e. c1 & c2 = Bitwise OR i.e. c1 | c2 = Bitwise XOR i.e. c1 ^ c2 = ones complement of c1 = ? left shift by 2 bits c1 << 2 = right shift by 2 bits c1 >> 2 =
Bitwise or: c1 | c2
<source lang="cpp"># include<stdio.h> main() {
char c1 = 4,c2 =6 ,c3 = 3; c3 = c1 | c2; printf("\n Bitwise OR i.e. c1 | c2 = %c",c3);
}</source>
Bitwise XOR: c1 ^ c2
<source lang="cpp"># include<stdio.h> main() {
char c1 = 4,c2 = 6,c3 = 3; c3 = c1 ^ c2; printf("\n Bitwise XOR i.e. c1 ^ c2 = %c",c3);
}</source>
Complement: ~
<source lang="cpp"># include<stdio.h> main() {
char c1 = 4,c2 = 6,c3 = 3; c3 = ~c1; printf("\n ones complement of c1 = %c",c3);
}</source>
Left shift operator
<source lang="cpp"># include<stdio.h> main() {
char c1 = 1,c2 = 2,c3 = 3; c3 = c1<<2; printf("\n left shift by 2 bits c1 << 2 = %c",c3);
}</source>
Right shift operation
<source lang="cpp"># include<stdio.h> main() {
char c1 = 1,c2 = 2,c3 = 3; c3 = c1>>2; printf("\n right shift by 2 bits c1 >> 2 = %c",c3);
}</source>
To divide value by 4
<source lang="cpp">#include <stdio.h> int main(){
int x, y = 8; x = y >> 2; printf("%d",x); x = y/4; printf("%d",x);
}</source>