This blog is under construction

Sunday 14 July 2013

C program to rotate bits of a number

Write a C program to rotate bits of a number(Left Rotation & Right Rotation).

Example: Input data is 252.  3 be the number of bits to be rotated.
Binary Equivalent of 252 is 1111 1100

Left Rotation: Left rotate 252 by 3 bits.
Find 252 << 3 => (1111 1100 << 3) => 1110 0000
Find 252 >> (8 -3) => (1111 1100 >> 5) => 0000 0111

255 & ((252 << 3) | (252 >> 5)) = 1110 0111 => 231
Binary equivalent of 255 is 1111 1111.  255 is used in above manipulation to get 8 bit output.

Right Rotation: Right rotate 252 by 3 bits.
Find 252 >> 3 => (1111 1100 >> 3) => 0001 1111
Find 252 << (8 - 3) => 1111 1100 << 5 => 1000 0000

255 & ((252 >> 3) | (252 << 5)) => 1001 1111 => 159



  #include <stdio.h>

  int main() {
        int value, n, lRotate, rRotate;

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

        /* threshold checking */
        if (value < 0 || value > 255) {
                printf("Threshold Value Exceeded!!\n");
                return 0;
        }

        /* number of bits to rotate */
        printf("No of bits to rotate(0-7):");
        scanf("%d", &n);

        if (n < 0 || n > 7) {
                printf("Threshold Value Exceeded!!\n");
                return 0;
        }

        /* left rotation */
        lRotate = 255 & ((value << n) | (value >> (8 - n)));

        /* right rotation */
        rRotate = 255 & ((value >> n) | (value << (8 - n)));

        /* print the results */
        printf("Left Rotation: %d\n", lRotate);
        printf("Right Rotation: %d\n", rRotate);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value(0-255):252
  No of bits to rotate(0-7):3
  Left Rotation: 231
  Right Rotation: 159


1 comment: