check if numbers from command line are powers of 2

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
-4
down vote

favorite












i can`t make a bash script who check if a input numbers in command line is an power of 2



input



# ./powerscript.sh xyzdf 4 8 12 -2 USAD


desired output : the desire output should be on seprated lines



4
8


because only 4 is 2^2
and 8 is 2^3



content of powerscript.sh



#!/bin/bash

function is_power_of_two ()
declare -i n=$1
(( n > 0 && (n & (n - 1)) == 0 ))


for number; do
if is_power_of_two "$number"; then
printf "%dn" "$number"
fi
done









share|improve this question









New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3




    Show us the content of powerscript.sh (post in the question itself)
    – sla3k
    yesterday






  • 3




    A mod only gives the remainder, so any even number mod 2 is 0.
    – KevinO
    yesterday










  • you could show the code exactly to understand please
    – Andrew
    yesterday






  • 1




    You need to make use of positional parameters in bash to pass arguments from the cli (here's a good read: gerardnico.com/lang/bash/argument).
    – sla3k
    yesterday






  • 1




    Since you mention Linux, you probably have the factor command. eg factor 32 will return 32: 2 2 2 2 2. You could check the output and determine if it just contains 2's
    – Stephen Harris
    yesterday














up vote
-4
down vote

favorite












i can`t make a bash script who check if a input numbers in command line is an power of 2



input



# ./powerscript.sh xyzdf 4 8 12 -2 USAD


desired output : the desire output should be on seprated lines



4
8


because only 4 is 2^2
and 8 is 2^3



content of powerscript.sh



#!/bin/bash

function is_power_of_two ()
declare -i n=$1
(( n > 0 && (n & (n - 1)) == 0 ))


for number; do
if is_power_of_two "$number"; then
printf "%dn" "$number"
fi
done









share|improve this question









New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3




    Show us the content of powerscript.sh (post in the question itself)
    – sla3k
    yesterday






  • 3




    A mod only gives the remainder, so any even number mod 2 is 0.
    – KevinO
    yesterday










  • you could show the code exactly to understand please
    – Andrew
    yesterday






  • 1




    You need to make use of positional parameters in bash to pass arguments from the cli (here's a good read: gerardnico.com/lang/bash/argument).
    – sla3k
    yesterday






  • 1




    Since you mention Linux, you probably have the factor command. eg factor 32 will return 32: 2 2 2 2 2. You could check the output and determine if it just contains 2's
    – Stephen Harris
    yesterday












up vote
-4
down vote

favorite









up vote
-4
down vote

favorite











i can`t make a bash script who check if a input numbers in command line is an power of 2



input



# ./powerscript.sh xyzdf 4 8 12 -2 USAD


desired output : the desire output should be on seprated lines



4
8


because only 4 is 2^2
and 8 is 2^3



content of powerscript.sh



#!/bin/bash

function is_power_of_two ()
declare -i n=$1
(( n > 0 && (n & (n - 1)) == 0 ))


for number; do
if is_power_of_two "$number"; then
printf "%dn" "$number"
fi
done









share|improve this question









New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











i can`t make a bash script who check if a input numbers in command line is an power of 2



input



# ./powerscript.sh xyzdf 4 8 12 -2 USAD


desired output : the desire output should be on seprated lines



4
8


because only 4 is 2^2
and 8 is 2^3



content of powerscript.sh



#!/bin/bash

function is_power_of_two ()
declare -i n=$1
(( n > 0 && (n & (n - 1)) == 0 ))


for number; do
if is_power_of_two "$number"; then
printf "%dn" "$number"
fi
done






linux bash scripting numeric-data






share|improve this question









New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday









RalfFriedl

4,7842725




4,7842725






New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Andrew

13




13




New contributor




Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 3




    Show us the content of powerscript.sh (post in the question itself)
    – sla3k
    yesterday






  • 3




    A mod only gives the remainder, so any even number mod 2 is 0.
    – KevinO
    yesterday










  • you could show the code exactly to understand please
    – Andrew
    yesterday






  • 1




    You need to make use of positional parameters in bash to pass arguments from the cli (here's a good read: gerardnico.com/lang/bash/argument).
    – sla3k
    yesterday






  • 1




    Since you mention Linux, you probably have the factor command. eg factor 32 will return 32: 2 2 2 2 2. You could check the output and determine if it just contains 2's
    – Stephen Harris
    yesterday












  • 3




    Show us the content of powerscript.sh (post in the question itself)
    – sla3k
    yesterday






  • 3




    A mod only gives the remainder, so any even number mod 2 is 0.
    – KevinO
    yesterday










  • you could show the code exactly to understand please
    – Andrew
    yesterday






  • 1




    You need to make use of positional parameters in bash to pass arguments from the cli (here's a good read: gerardnico.com/lang/bash/argument).
    – sla3k
    yesterday






  • 1




    Since you mention Linux, you probably have the factor command. eg factor 32 will return 32: 2 2 2 2 2. You could check the output and determine if it just contains 2's
    – Stephen Harris
    yesterday







3




3




Show us the content of powerscript.sh (post in the question itself)
– sla3k
yesterday




Show us the content of powerscript.sh (post in the question itself)
– sla3k
yesterday




3




3




A mod only gives the remainder, so any even number mod 2 is 0.
– KevinO
yesterday




A mod only gives the remainder, so any even number mod 2 is 0.
– KevinO
yesterday












you could show the code exactly to understand please
– Andrew
yesterday




you could show the code exactly to understand please
– Andrew
yesterday




1




1




You need to make use of positional parameters in bash to pass arguments from the cli (here's a good read: gerardnico.com/lang/bash/argument).
– sla3k
yesterday




You need to make use of positional parameters in bash to pass arguments from the cli (here's a good read: gerardnico.com/lang/bash/argument).
– sla3k
yesterday




1




1




Since you mention Linux, you probably have the factor command. eg factor 32 will return 32: 2 2 2 2 2. You could check the output and determine if it just contains 2's
– Stephen Harris
yesterday




Since you mention Linux, you probably have the factor command. eg factor 32 will return 32: 2 2 2 2 2. You could check the output and determine if it just contains 2's
– Stephen Harris
yesterday










4 Answers
4






active

oldest

votes

















up vote
5
down vote



accepted










The number is a power of 2 if its Hamming weight is exactly 1.



To calculate a number's Hamming weight is the same as calculate the number of 1s in its binary representation.



The following is a short bash script that does that:



#!/bin/bash

# loop over all numbers on the command line
# note: we don't verify that these are in fact numbers
for number do
w=0 # Hamming weight (count of bits that are 1)
n=$number # work on $n to save $number for later

# test the last bit of the number, and right-shift once
# repeat until number is zero
while (( n > 0 )); do
if (( (n & 1) == 1 )); then
# last bit was 1, count it
w=$(( w + 1 ))
fi

if (( w > 1 )); then
# early bail-out: not a power of 2
break
fi

# right-shift number
n=$(( n >> 1 ))
done

if (( w == 1 )); then
# this was a power of 2
printf '%dn' "$number"
fi
done


Testing:



$ bash script.sh xyzdf 4 8 12 -2 USAD
4
8


Note: There are more efficient ways to do this, and bash is a particularly bad choice of language for it.






share|improve this answer






















  • thank you very much, i understand now, have a great day
    – Andrew
    yesterday










  • done , sorry men
    – Andrew
    yesterday










  • men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
    – Andrew
    yesterday











  • @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
    – Kusalananda
    yesterday











  • so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
    – Andrew
    yesterday

















up vote
9
down vote













There's a nice shortcut to check that a number is a power of two.



If you represent such a number in binary, it will be a single 1 followed by a string of zeroes, for instance 0b100000 for the number 32. If you subtract one from it, you'll get ones where you had the zeroes and a zero where you had the 1, for instance 0b011111 for the number 31, which is 32 - 1. If you do a bitwise and operation on these two, you'll get a zero. That property is only valid on numbers that are powers of two (and zero).



So:



function is_power_of_two () 
declare -i n=$1
(( n > 0 && (n & (n - 1)) == 0 ))



Use it as:



for number; do
if is_power_of_two "$number"; then
printf "%dn" "$number"
fi
done


And execution output:



$ ./power2.sh 1 2 3 4 5 7 8 9 31 32 33 -2
1
2
4
8
32





share|improve this answer
















  • 3




    this is very clever
    – glenn jackman
    yesterday










  • i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
    – Andrew
    yesterday






  • 1




    that's a real beauty =}
    – tink
    yesterday

















up vote
3
down vote













Another pure bash approach



isPowerOf2 () 
local n=$1 i=0
for ((; n>1; n/=2, i++)); do :; done
(($1 - (2 ** $i) == 0))



and



$ for n in 1..17; do isPowerOf2 $n && echo $n; done
1
2
4
8
16


Or looking at the octal representation of the number:



isPowerOf2() $octal =~ ^[12]0*$ ]]



Or awk perhaps



$ seq 17 | awk 'lg = log($1) / log(2) lg == int(lg)'
1
2
4
8
16





share|improve this answer






















  • i try this code but generate errors
    – Andrew
    yesterday










  • which code? what errors?
    – glenn jackman
    yesterday










  • syntax error near unexpected
    – Andrew
    yesterday










  • Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
    – glenn jackman
    yesterday











  • yes , sure im using
    – Andrew
    yesterday

















up vote
2
down vote













Got the factor command? Try



factor $number | sed 's/^[^:]*:|[2 ]//g;'


and test for empty result.






share|improve this answer




















    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "106"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Andrew is a new contributor. Be nice, and check out our Code of Conduct.









     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f481552%2fcheck-if-numbers-from-command-line-are-powers-of-2%23new-answer', 'question_page');

    );

    Post as a guest






























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    5
    down vote



    accepted










    The number is a power of 2 if its Hamming weight is exactly 1.



    To calculate a number's Hamming weight is the same as calculate the number of 1s in its binary representation.



    The following is a short bash script that does that:



    #!/bin/bash

    # loop over all numbers on the command line
    # note: we don't verify that these are in fact numbers
    for number do
    w=0 # Hamming weight (count of bits that are 1)
    n=$number # work on $n to save $number for later

    # test the last bit of the number, and right-shift once
    # repeat until number is zero
    while (( n > 0 )); do
    if (( (n & 1) == 1 )); then
    # last bit was 1, count it
    w=$(( w + 1 ))
    fi

    if (( w > 1 )); then
    # early bail-out: not a power of 2
    break
    fi

    # right-shift number
    n=$(( n >> 1 ))
    done

    if (( w == 1 )); then
    # this was a power of 2
    printf '%dn' "$number"
    fi
    done


    Testing:



    $ bash script.sh xyzdf 4 8 12 -2 USAD
    4
    8


    Note: There are more efficient ways to do this, and bash is a particularly bad choice of language for it.






    share|improve this answer






















    • thank you very much, i understand now, have a great day
      – Andrew
      yesterday










    • done , sorry men
      – Andrew
      yesterday










    • men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
      – Andrew
      yesterday











    • @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
      – Kusalananda
      yesterday











    • so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
      – Andrew
      yesterday














    up vote
    5
    down vote



    accepted










    The number is a power of 2 if its Hamming weight is exactly 1.



    To calculate a number's Hamming weight is the same as calculate the number of 1s in its binary representation.



    The following is a short bash script that does that:



    #!/bin/bash

    # loop over all numbers on the command line
    # note: we don't verify that these are in fact numbers
    for number do
    w=0 # Hamming weight (count of bits that are 1)
    n=$number # work on $n to save $number for later

    # test the last bit of the number, and right-shift once
    # repeat until number is zero
    while (( n > 0 )); do
    if (( (n & 1) == 1 )); then
    # last bit was 1, count it
    w=$(( w + 1 ))
    fi

    if (( w > 1 )); then
    # early bail-out: not a power of 2
    break
    fi

    # right-shift number
    n=$(( n >> 1 ))
    done

    if (( w == 1 )); then
    # this was a power of 2
    printf '%dn' "$number"
    fi
    done


    Testing:



    $ bash script.sh xyzdf 4 8 12 -2 USAD
    4
    8


    Note: There are more efficient ways to do this, and bash is a particularly bad choice of language for it.






    share|improve this answer






















    • thank you very much, i understand now, have a great day
      – Andrew
      yesterday










    • done , sorry men
      – Andrew
      yesterday










    • men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
      – Andrew
      yesterday











    • @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
      – Kusalananda
      yesterday











    • so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
      – Andrew
      yesterday












    up vote
    5
    down vote



    accepted







    up vote
    5
    down vote



    accepted






    The number is a power of 2 if its Hamming weight is exactly 1.



    To calculate a number's Hamming weight is the same as calculate the number of 1s in its binary representation.



    The following is a short bash script that does that:



    #!/bin/bash

    # loop over all numbers on the command line
    # note: we don't verify that these are in fact numbers
    for number do
    w=0 # Hamming weight (count of bits that are 1)
    n=$number # work on $n to save $number for later

    # test the last bit of the number, and right-shift once
    # repeat until number is zero
    while (( n > 0 )); do
    if (( (n & 1) == 1 )); then
    # last bit was 1, count it
    w=$(( w + 1 ))
    fi

    if (( w > 1 )); then
    # early bail-out: not a power of 2
    break
    fi

    # right-shift number
    n=$(( n >> 1 ))
    done

    if (( w == 1 )); then
    # this was a power of 2
    printf '%dn' "$number"
    fi
    done


    Testing:



    $ bash script.sh xyzdf 4 8 12 -2 USAD
    4
    8


    Note: There are more efficient ways to do this, and bash is a particularly bad choice of language for it.






    share|improve this answer














    The number is a power of 2 if its Hamming weight is exactly 1.



    To calculate a number's Hamming weight is the same as calculate the number of 1s in its binary representation.



    The following is a short bash script that does that:



    #!/bin/bash

    # loop over all numbers on the command line
    # note: we don't verify that these are in fact numbers
    for number do
    w=0 # Hamming weight (count of bits that are 1)
    n=$number # work on $n to save $number for later

    # test the last bit of the number, and right-shift once
    # repeat until number is zero
    while (( n > 0 )); do
    if (( (n & 1) == 1 )); then
    # last bit was 1, count it
    w=$(( w + 1 ))
    fi

    if (( w > 1 )); then
    # early bail-out: not a power of 2
    break
    fi

    # right-shift number
    n=$(( n >> 1 ))
    done

    if (( w == 1 )); then
    # this was a power of 2
    printf '%dn' "$number"
    fi
    done


    Testing:



    $ bash script.sh xyzdf 4 8 12 -2 USAD
    4
    8


    Note: There are more efficient ways to do this, and bash is a particularly bad choice of language for it.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    Kusalananda

    115k15218349




    115k15218349











    • thank you very much, i understand now, have a great day
      – Andrew
      yesterday










    • done , sorry men
      – Andrew
      yesterday










    • men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
      – Andrew
      yesterday











    • @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
      – Kusalananda
      yesterday











    • so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
      – Andrew
      yesterday
















    • thank you very much, i understand now, have a great day
      – Andrew
      yesterday










    • done , sorry men
      – Andrew
      yesterday










    • men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
      – Andrew
      yesterday











    • @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
      – Kusalananda
      yesterday











    • so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
      – Andrew
      yesterday















    thank you very much, i understand now, have a great day
    – Andrew
    yesterday




    thank you very much, i understand now, have a great day
    – Andrew
    yesterday












    done , sorry men
    – Andrew
    yesterday




    done , sorry men
    – Andrew
    yesterday












    men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
    – Andrew
    yesterday





    men, should be modify the code because when i run ./powerscript.sh xyz 4 8 -2 he show 4 , 8 but not corectly when i have char
    – Andrew
    yesterday













    @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
    – Kusalananda
    yesterday





    @AndrewThe script will not output the string since its not even a number. This is exactly the behaviour that you describe in your updated question.
    – Kusalananda
    yesterday













    so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
    – Andrew
    yesterday




    so , the input is ./powerscript.sh xyz 4 -2 uso 8 63 ASDASD and i want to show on seprated lines on numbers which are power of two but the command line will be entered with xyz and ASDASD
    – Andrew
    yesterday












    up vote
    9
    down vote













    There's a nice shortcut to check that a number is a power of two.



    If you represent such a number in binary, it will be a single 1 followed by a string of zeroes, for instance 0b100000 for the number 32. If you subtract one from it, you'll get ones where you had the zeroes and a zero where you had the 1, for instance 0b011111 for the number 31, which is 32 - 1. If you do a bitwise and operation on these two, you'll get a zero. That property is only valid on numbers that are powers of two (and zero).



    So:



    function is_power_of_two () 
    declare -i n=$1
    (( n > 0 && (n & (n - 1)) == 0 ))



    Use it as:



    for number; do
    if is_power_of_two "$number"; then
    printf "%dn" "$number"
    fi
    done


    And execution output:



    $ ./power2.sh 1 2 3 4 5 7 8 9 31 32 33 -2
    1
    2
    4
    8
    32





    share|improve this answer
















    • 3




      this is very clever
      – glenn jackman
      yesterday










    • i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
      – Andrew
      yesterday






    • 1




      that's a real beauty =}
      – tink
      yesterday














    up vote
    9
    down vote













    There's a nice shortcut to check that a number is a power of two.



    If you represent such a number in binary, it will be a single 1 followed by a string of zeroes, for instance 0b100000 for the number 32. If you subtract one from it, you'll get ones where you had the zeroes and a zero where you had the 1, for instance 0b011111 for the number 31, which is 32 - 1. If you do a bitwise and operation on these two, you'll get a zero. That property is only valid on numbers that are powers of two (and zero).



    So:



    function is_power_of_two () 
    declare -i n=$1
    (( n > 0 && (n & (n - 1)) == 0 ))



    Use it as:



    for number; do
    if is_power_of_two "$number"; then
    printf "%dn" "$number"
    fi
    done


    And execution output:



    $ ./power2.sh 1 2 3 4 5 7 8 9 31 32 33 -2
    1
    2
    4
    8
    32





    share|improve this answer
















    • 3




      this is very clever
      – glenn jackman
      yesterday










    • i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
      – Andrew
      yesterday






    • 1




      that's a real beauty =}
      – tink
      yesterday












    up vote
    9
    down vote










    up vote
    9
    down vote









    There's a nice shortcut to check that a number is a power of two.



    If you represent such a number in binary, it will be a single 1 followed by a string of zeroes, for instance 0b100000 for the number 32. If you subtract one from it, you'll get ones where you had the zeroes and a zero where you had the 1, for instance 0b011111 for the number 31, which is 32 - 1. If you do a bitwise and operation on these two, you'll get a zero. That property is only valid on numbers that are powers of two (and zero).



    So:



    function is_power_of_two () 
    declare -i n=$1
    (( n > 0 && (n & (n - 1)) == 0 ))



    Use it as:



    for number; do
    if is_power_of_two "$number"; then
    printf "%dn" "$number"
    fi
    done


    And execution output:



    $ ./power2.sh 1 2 3 4 5 7 8 9 31 32 33 -2
    1
    2
    4
    8
    32





    share|improve this answer












    There's a nice shortcut to check that a number is a power of two.



    If you represent such a number in binary, it will be a single 1 followed by a string of zeroes, for instance 0b100000 for the number 32. If you subtract one from it, you'll get ones where you had the zeroes and a zero where you had the 1, for instance 0b011111 for the number 31, which is 32 - 1. If you do a bitwise and operation on these two, you'll get a zero. That property is only valid on numbers that are powers of two (and zero).



    So:



    function is_power_of_two () 
    declare -i n=$1
    (( n > 0 && (n & (n - 1)) == 0 ))



    Use it as:



    for number; do
    if is_power_of_two "$number"; then
    printf "%dn" "$number"
    fi
    done


    And execution output:



    $ ./power2.sh 1 2 3 4 5 7 8 9 31 32 33 -2
    1
    2
    4
    8
    32






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered yesterday









    Filipe Brandenburger

    5,7241624




    5,7241624







    • 3




      this is very clever
      – glenn jackman
      yesterday










    • i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
      – Andrew
      yesterday






    • 1




      that's a real beauty =}
      – tink
      yesterday












    • 3




      this is very clever
      – glenn jackman
      yesterday










    • i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
      – Andrew
      yesterday






    • 1




      that's a real beauty =}
      – tink
      yesterday







    3




    3




    this is very clever
    – glenn jackman
    yesterday




    this is very clever
    – glenn jackman
    yesterday












    i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
    – Andrew
    yesterday




    i have a checker bro and he said im not displaying corectly the numbers which is power of 2 can you have any ideas to get the points when i check
    – Andrew
    yesterday




    1




    1




    that's a real beauty =}
    – tink
    yesterday




    that's a real beauty =}
    – tink
    yesterday










    up vote
    3
    down vote













    Another pure bash approach



    isPowerOf2 () 
    local n=$1 i=0
    for ((; n>1; n/=2, i++)); do :; done
    (($1 - (2 ** $i) == 0))



    and



    $ for n in 1..17; do isPowerOf2 $n && echo $n; done
    1
    2
    4
    8
    16


    Or looking at the octal representation of the number:



    isPowerOf2() $octal =~ ^[12]0*$ ]]



    Or awk perhaps



    $ seq 17 | awk 'lg = log($1) / log(2) lg == int(lg)'
    1
    2
    4
    8
    16





    share|improve this answer






















    • i try this code but generate errors
      – Andrew
      yesterday










    • which code? what errors?
      – glenn jackman
      yesterday










    • syntax error near unexpected
      – Andrew
      yesterday










    • Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
      – glenn jackman
      yesterday











    • yes , sure im using
      – Andrew
      yesterday














    up vote
    3
    down vote













    Another pure bash approach



    isPowerOf2 () 
    local n=$1 i=0
    for ((; n>1; n/=2, i++)); do :; done
    (($1 - (2 ** $i) == 0))



    and



    $ for n in 1..17; do isPowerOf2 $n && echo $n; done
    1
    2
    4
    8
    16


    Or looking at the octal representation of the number:



    isPowerOf2() $octal =~ ^[12]0*$ ]]



    Or awk perhaps



    $ seq 17 | awk 'lg = log($1) / log(2) lg == int(lg)'
    1
    2
    4
    8
    16





    share|improve this answer






















    • i try this code but generate errors
      – Andrew
      yesterday










    • which code? what errors?
      – glenn jackman
      yesterday










    • syntax error near unexpected
      – Andrew
      yesterday










    • Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
      – glenn jackman
      yesterday











    • yes , sure im using
      – Andrew
      yesterday












    up vote
    3
    down vote










    up vote
    3
    down vote









    Another pure bash approach



    isPowerOf2 () 
    local n=$1 i=0
    for ((; n>1; n/=2, i++)); do :; done
    (($1 - (2 ** $i) == 0))



    and



    $ for n in 1..17; do isPowerOf2 $n && echo $n; done
    1
    2
    4
    8
    16


    Or looking at the octal representation of the number:



    isPowerOf2() $octal =~ ^[12]0*$ ]]



    Or awk perhaps



    $ seq 17 | awk 'lg = log($1) / log(2) lg == int(lg)'
    1
    2
    4
    8
    16





    share|improve this answer














    Another pure bash approach



    isPowerOf2 () 
    local n=$1 i=0
    for ((; n>1; n/=2, i++)); do :; done
    (($1 - (2 ** $i) == 0))



    and



    $ for n in 1..17; do isPowerOf2 $n && echo $n; done
    1
    2
    4
    8
    16


    Or looking at the octal representation of the number:



    isPowerOf2() $octal =~ ^[12]0*$ ]]



    Or awk perhaps



    $ seq 17 | awk 'lg = log($1) / log(2) lg == int(lg)'
    1
    2
    4
    8
    16






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    glenn jackman

    49.3k469106




    49.3k469106











    • i try this code but generate errors
      – Andrew
      yesterday










    • which code? what errors?
      – glenn jackman
      yesterday










    • syntax error near unexpected
      – Andrew
      yesterday










    • Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
      – glenn jackman
      yesterday











    • yes , sure im using
      – Andrew
      yesterday
















    • i try this code but generate errors
      – Andrew
      yesterday










    • which code? what errors?
      – glenn jackman
      yesterday










    • syntax error near unexpected
      – Andrew
      yesterday










    • Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
      – glenn jackman
      yesterday











    • yes , sure im using
      – Andrew
      yesterday















    i try this code but generate errors
    – Andrew
    yesterday




    i try this code but generate errors
    – Andrew
    yesterday












    which code? what errors?
    – glenn jackman
    yesterday




    which code? what errors?
    – glenn jackman
    yesterday












    syntax error near unexpected
    – Andrew
    yesterday




    syntax error near unexpected
    – Andrew
    yesterday












    Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
    – glenn jackman
    yesterday





    Is your script using #!/bin/bash ? Are you invoking it like sh myscript.sh 4 8 foo?
    – glenn jackman
    yesterday













    yes , sure im using
    – Andrew
    yesterday




    yes , sure im using
    – Andrew
    yesterday










    up vote
    2
    down vote













    Got the factor command? Try



    factor $number | sed 's/^[^:]*:|[2 ]//g;'


    and test for empty result.






    share|improve this answer
























      up vote
      2
      down vote













      Got the factor command? Try



      factor $number | sed 's/^[^:]*:|[2 ]//g;'


      and test for empty result.






      share|improve this answer






















        up vote
        2
        down vote










        up vote
        2
        down vote









        Got the factor command? Try



        factor $number | sed 's/^[^:]*:|[2 ]//g;'


        and test for empty result.






        share|improve this answer












        Got the factor command? Try



        factor $number | sed 's/^[^:]*:|[2 ]//g;'


        and test for empty result.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        RudiC

        2,9311211




        2,9311211




















            Andrew is a new contributor. Be nice, and check out our Code of Conduct.









             

            draft saved


            draft discarded


















            Andrew is a new contributor. Be nice, and check out our Code of Conduct.












            Andrew is a new contributor. Be nice, and check out our Code of Conduct.











            Andrew is a new contributor. Be nice, and check out our Code of Conduct.













             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f481552%2fcheck-if-numbers-from-command-line-are-powers-of-2%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            How to check contact read email or not when send email to Individual?

            Displaying single band from multi-band raster using QGIS

            How many registers does an x86_64 CPU actually have?