Q:

Check number of processes in MPI for power of two

Sorry if this is a stupid question but I just want to know whats the actual meaning of the if statement below.
int rank, numprocs;
MPI_Status status;

MPI_Init(&argc,&argv);
MPI_Comm_size( MPI_COMM_WORLD, &numprocs );
MPI_Comm_rank( MPI_COMM_WORLD, &rank     );

if( numprocs&(numprocs-1) )
{
    if( rank==0 ) printf( "numprocs must be a power of 2.\n" );
    MPI_Finalize();
    return EXIT_FAILURE;
}

I was told that "numprocs&(numprocs-1)" is used to check if the numprocs is the power of 2, but how does it work actually? What is the output of the statement? Is it boolean or int?
Thanks.

A:

The & operator is bitwise AND operator.
If numprocs is the power of 2, its binary representation will contain exactly one bit whose bit is 1.
For example, if numprocs = 16, numprocs - 1 = 15 and their AND will be zero because borrowing in subtraction happens from LSB to the bit whose value is 1.
  10000 (16)
& 01111 (15)
------------
  00000 ( 0)

Contrary, if numprocs is positive and not the power of 2, its binary representations will contain more than one bit whose bit is 1.
For example, if numprocs = 20, numprocs - 1 = 19 and borrowing in subtraction will stop before reaching the topmost bit, so bit whose value is 1 survives and the result won't be zero.
  10100 (20)
& 10011 (19)
------------
  10000 (16)

The result is int. if statement in C will treat zero as false and non-zero as true.

