sh Arithmetic Expansion Is a Power of 2

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

$ ispow2() { return $((!($1!=0&&($1&$1-1)==0))); }
$ i=0
$ while [ $i -lt 100 ]; do
>     if ispow2 $((i=i+1)); then
>         echo $i
>     fi
> done
1
2
4
8
16
32
64

$1!=0 0 is not a power of 2.

($1&$1-1)==0 Unset the lowest bit. If it was the only bit then the number was a power of 2.

The additional ! was for correcting the value to what the shell expects, which is the opposite of the conventional true/false values (zero for true and non-zero for false, vs zero for false and non-zero for true).



Got any sh Question?