This blog is under construction

Sunday 14 July 2013

C program to shift the bits of a number(left shift and right shift)

Write a C program to shift the bits of a number(left shift and right shift).



  #include <stdio.h>

  int main() {
        int value, n, lshift, rshift;

        /* get the input value from user */
        printf("Enter your input value:");
        scanf("%d", &value);

        /* get no of bits to be shifted from user */
        printf("Enter the number bits to be shifted:");
        scanf("%d", &n);

        /* left shift value by n bits */
        lshift = value << n;

        /* Right shift value by n bits */
        rshift = value >> n;

        /* print the left shift output */
        printf("Left Shift:\n");
        printf("%d << %d is %d\n", value, n, lshift);

        /* print the right shift output */
        printf("Right Shift:\n");
        printf("%d >> %d is %d\n", value, n, rshift);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:8
  Enter the number bits to be shifted:2
  Left Shift:
  8 << 2 is 32
  Right Shift:
  8 >> 2 is 2
  

No comments:

Post a Comment