Problems on Bit Manipulations

Check if two numbers have opposite sign


We can use the operation
if    (x ^ y) < 0    where x and y are non zero numbers

{  True   --- if numbers of opposite sign
{  False  --- if numbers of same sign

int  x=-10,y=2;
System.out.println(((x ^ y) < 0));

Output :-

False


Check if number is power of 2

We can use   

x & (x - 1)) == 0    True   --- if numbers is a power of 2
                                 False  --- if numbers is not a power of 2

int  x=16;
System.out.println((x & (x - 1))==0);
Output :-
True



More bitwise tricks

x&(x-1)           :---------------- Returns number x with the lowest bit set off
x ^ ( x & (x-1 )  :---------------- Returns the lowest bit of a number x
x & 1<<n          :----------------  Returns 1<<n if the n-th bit is set in x
x | 1<<n          :----------------  Returns the number x with the n-th bit set
x ^ 1<<n          :----------------  Toggles the state of the n-th bit in the number x



Displaying all subsets of a subset.

Consider a number 10110

Required Output :-
00000
00010
00100
00110
10000
10010
10100
10110

Algorithm

start
    N; //an integer
    X = N
    while true
        print X
        if( X == 0 )
            break;
        X = (X-1) & N;
    end while
end

Comments

Popular posts from this blog

When to use getClass() and instanceOf in Java

Fix double check locking in Java 5

Generate Heap Dump in Unix