Operating System - HP-UX
1842308 Members
2363 Online
110188 Solutions
New Discussion

Re: checking if number is power of 2

 
SOLVED
Go to solution
andi_1
Frequent Advisor

checking if number is power of 2

Hi guys,

Do you know if shell provides some kind of resource that will allow to check if the number is a number power of 2, such as: 4, 16, 32, etc.?

Thank you!
4 REPLIES 4
Rodney Hills
Honored Contributor
Solution

Re: checking if number is power of 2

Here is something that can check up to a power of 2^32.

$num=32
x=`echo "obase=2 ; $num" | bc`
y=${x%%0*}
if [ $y = "1" ] ; then
echo "power of 2!"
else
echo "not power of 2"
fi

By using bc to output in base 2, then a power of 2 number will be a 1 followed by all zeroes.
The y= will strip off the trailing zeroes and if we are left with only "1", it is a power of 2.

-- Rod Hills
There be dragons...
A. Clay Stephenson
Acclaimed Contributor

Re: checking if number is power of 2

Here is one rather simple, all-shell method:

# return 0 if not power of 2; 1 otherwise
is_power_of_two()
{
X=$1
shift
if [ ${X} -lt 0 ]
then
X=$((${X} * -1))
fi
Y=1
while [ ${X} -ge ${Y} -a ${Y} -gt 0 ]
do
if [ ${X} -eq ${Y} ]
then
return 1
fi
Y=$((${Y} * 2))
done
return 0
} # is_power_of_two

while [ $# -ge 1 ]
do
echo "Value: ${1} \c"
is_power_of_two ${1}
STAT=$?
if [ ${STAT} -ne 0 ]
then
echo "Yes"
else
echo "No"
fi
shift
done

------------------------------------------
The integer underflow takes care of falling off the edge of the world.
If it ain't broke, I can fix that.
andi_1
Frequent Advisor

Re: checking if number is power of 2

Actually, I did a little different:

tmp=$1

while true
do

let tmp3=$tmp1*2

tmp1=$tmp3

if [ $tmp3 -eq $tmp ]; then
#echo "number is of power 2"
retStatus=0
break
fi

if [ $tmp3 -gt $tmp ]; then
echo "\tNumber is not power of 2"
retStatus=1
break
fi

done

return $retStatus

Instead of dividing, I multiplied.

zhaogui
Super Advisor

Re: checking if number is power of 2

Here is my script,
#cat test2power
echo "Please input a number:\c"
read num
count=0;
while true
do
let newnum=$num\/2;
let remain=$num\%2;
let count=$count+1;
if (( $remain == 1 ))
then
echo "It is not power of 2!"
exit 1
fi
if (( $newnum < 2 ))
then
echo "It is $count power of 2"
exit 0
fi
num=$newnum
done