Please explain this C++ statement. Thanks.

Hi there.

There is a piece of code I do not understand

1
2
3
  bool CFFT::Forward(const complex *const Input, complex *const Output, const unsigned int N)
{
	if (!Input || !Output || N < 1 || N & (N - 1))


I understand the pointers, etc. The line I need an explanation about is highlighted. I understand all logical operators, fine, but what does it mean:

N & (N - 1)

Also what about the negation: !input ? Does it mean no input array was provided?

Thanks
Last edited on
> what does it mean: N & (N - 1)

If N is a power of two, ( N & (N-1) ) == 0, if not ( N & (N-1) ) is non-zero. (Why is this so? Can you explain?)

> what about the negation: !input ? Does it mean no input array was provided?

Yes. !Input is equivalent to Input != nullptr


if (!Input || !Output || N < 1 || N & (N - 1))

Pseudo code: if( Input is null or Output is null or N is zero or N is not a power of two )

1
2
3
4
5
6
7
#include <iostream>

int main()
{
    for( unsigned int N = 1 ; N < 5000 ; ++N )
        if( ( N & (N-1) ) == 0 ) std::cout << N << ' ' ;
}

clang++ -std=c++11 -stdlib=libc++ -O2 -Wall -Wextra -pedantic-errors main.cpp -lsupc++ && ./a.out
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 

http://coliru.stacked-crooked.com/a/d6f7c54cde801ec9
Well, if the number N is a power of two then in the binary representation it will be a unit in the left most position followed by a bunch of zeroes e.g. 16 will be 10000. If you subtract a unit from this number then the binary representation will look as a bunch of units from the right most position to the position where the unit just was but that position will be replaced by a zero, e.g: 01111. If you take an & operation then you will come up with a zero because 1 & 0 == 0. Clear, Thanks, A.
Last edited on
Topic archived. No new replies allowed.