Bitwise AND, OR, EXOR

<syntaxhighlight lang="c" name="bitwise">

  1. include<stdio.h>

int main() {

   int a;
   printf("Enter a number\n");
   scanf("%d", &a);
   printf("The third bit (from right) of  %d  is made 0  and we get %d\n", a, a& (-1<<3 | 11)); // -1 has all bits 1, so -1<<3 will have the rightmost 3 bits 0 and rest 1, and -1<<3 | 11 will have the 3rd bit from right as 0 and all other bits 1 

} </syntaxhighlight>

Bitwise NOT

<syntaxhighlight lang="c" name="bitwisenot">

  1. include<stdio.h>

int main() {

   unsigned int a;
   printf("Enter a number\n");
   scanf("%u", &a);
   printf("Negation of %u is %u\n", a, ~a); //~a will have all bits of a inverted (0's become 1 and 1's become 0)

} </syntaxhighlight>

Left Shift

<syntaxhighlight lang="c" name="leftshift">

  1. include<stdio.h>

int main() {

   int a, b;
   printf("Enter a number and a power of 2\n");
   scanf("%d %d", &a, &b);
   printf("%d multiplied by 2^%d is %d\n", a, b, a << b); 

} </syntaxhighlight>

Right Shift

<syntaxhighlight lang="c" name="rightshift">

  1. include<stdio.h>

int main() {

   int a, b;
   printf("Enter a number and a power of 2\n");
   scanf("%d %d", &a, &b);
   printf("%d divided by 2^%d is %d\n", a, b, a >> b);

} </syntaxhighlight>





blog comments powered by Disqus



This work is licensed under the CC By-SA 3.0 , without all the cruft that would otherwise be put at the bottom of the page.

Sister Sites: GATE CSE Wiki, GATE CSE, Aptitude Overflow