Wednesday, January 1, 2014

To find whether a number is in power of 2 using complement and gate (very short)

A number occurring in power of has a specialty when written in its binary representation:

1     = 0000 0001
2     = 0000 0010
4     = 0000 0100
8     = 0000 1000
16   = 0001 0000
32   = 0010 0000
64   = 0100 0000
128 = 1000 0000

What happens when I subtract one from these above numbers

1-1=0          0000 0000
2-1=1          0000 0001
4-1=3          0000 0011
8-1=7          0000 0111
16-1=15      0000 1111
32-1=31      0001 1111
64-1=63      0011 1111
128-1=127   0111 1111

Before moving further we will look at Complement Operator(~) in C.
Complement of a binary number changes all 1 bits to 0 and all zero bits to 1

~(1011 0110) = 0100 1001

It is similar to XOR toggling all bits
          1011 0110
XOR    1111 1111
------------------------
           0100 1001

Never mind!

Looking at numbers in power of two and their subtraction by 1, we can establish a pattern

For example, let us take 16
 16 =  0001 0000
 ~(16) = ~(0001 0000) = 1110 1111
16-1=15 = 0000 1111

If we AND  ~16 and (16-1), it equals (16-1)

~(16) =         1110 1111
16-1=15=      0000 1111
----------------------------------
 16-1=15=      0000 1111

Hence the method to find whether the number is power of two or not.

#include<stdio.h>
int main()
{
    int num;
    printf("\nEnter number:");
    scanf("%d",&num);
    if(((num-1)&(~num))==(num-1))
        printf("%d is in power of 2",num);
    else
        printf("%d is not in power of 2",num);

    return 0;
}

Although, this short method does not tell us which power of 2 is the number like previous methods discussed. You can verify this method for numbers that are not in power of two.






No comments:

Post a Comment