Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Power of 2

Power of 2

Scheduled Pinned Locked Moved C / C++ / MFC
question
38 Posts 12 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    RichardS
    wrote on last edited by
    #1

    Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

    T R D B T 7 Replies Last reply
    0
    • R RichardS

      Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

      T Offline
      T Offline
      toxcct
      wrote on last edited by
      #2

      :sigh:

      R C S 4 Replies Last reply
      0
      • R RichardS

        Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

        R Offline
        R Offline
        Russell
        wrote on last edited by
        #3

        if a number is a power of 2 than looking at the bits that composed that value must be all '0' but only one '1'. So, if int is a 32 bit value, you can look for 31 '0' and 1 '1'. But you need olso a loop! But it is quite fast. Let me know if here is a faster bit function to count the ones/zeros Bye

        Have a nice code day ;)

        R 1 Reply Last reply
        0
        • T toxcct

          :sigh:

          R Offline
          R Offline
          RichardS
          wrote on last edited by
          #4

          Thanks :) "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

          1 Reply Last reply
          0
          • R Russell

            if a number is a power of 2 than looking at the bits that composed that value must be all '0' but only one '1'. So, if int is a 32 bit value, you can look for 31 '0' and 1 '1'. But you need olso a loop! But it is quite fast. Let me know if here is a faster bit function to count the ones/zeros Bye

            Have a nice code day ;)

            R Offline
            R Offline
            RichardS
            wrote on last edited by
            #5

            Yip, this was my way to begin with. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

            R 1 Reply Last reply
            0
            • T toxcct

              :sigh:

              C Offline
              C Offline
              Cedric Moonen
              wrote on last edited by
              #6

              I think you will have problems when comparinf the floats, due to the precision.

              T 1 Reply Last reply
              0
              • R RichardS

                Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

                D Offline
                D Offline
                Divyang Mithaiwala
                wrote on last edited by
                #7

                Hello RichardS, Try this one.

                double val = 0.0;
                val = log10(y) / log10(2.0);
                
                //Check that 'val' is pure int (Here you use ur own code is u optimize)
                int val2 = int(val);
                
                if (val == val2) 
                     // y is power of 2
                else
                     // y is not power of 2
                

                here 'y' is value u want to check for power of 2. Best of luck


                Divyang Mithaiwala System Engineer & Software Developer

                T D 2 Replies Last reply
                0
                • T toxcct

                  :sigh:

                  S Offline
                  S Offline
                  Stephen Hewitt
                  wrote on last edited by
                  #8

                  2^3 = 8 but floor(sqrt(8)) != sqrt(8)? Steve

                  1 Reply Last reply
                  0
                  • C Cedric Moonen

                    I think you will have problems when comparinf the floats, due to the precision.

                    T Offline
                    T Offline
                    toxcct
                    wrote on last edited by
                    #9

                    true, but that was a starting point. it would be better to use double at least, but still remains the precision problem.

                    1 Reply Last reply
                    0
                    • D Divyang Mithaiwala

                      Hello RichardS, Try this one.

                      double val = 0.0;
                      val = log10(y) / log10(2.0);
                      
                      //Check that 'val' is pure int (Here you use ur own code is u optimize)
                      int val2 = int(val);
                      
                      if (val == val2) 
                           // y is power of 2
                      else
                           // y is not power of 2
                      

                      here 'y' is value u want to check for power of 2. Best of luck


                      Divyang Mithaiwala System Engineer & Software Developer

                      T Offline
                      T Offline
                      toxcct
                      wrote on last edited by
                      #10

                      we are on a standard C++ forum, not managed/CLI...

                      D 1 Reply Last reply
                      0
                      • R RichardS

                        Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

                        B Offline
                        B Offline
                        BadKarma
                        wrote on last edited by
                        #11

                        Hi, you could use ::log to check if its a power of 2 math: y = 2^x -> x = log(y)/log(2) so you can use:

                        int y = 1024;
                        if(y == (int)(::pow(2.0, ::floor(::log((double)y)/::log(2.0)))))
                        {
                          //  true
                        }
                        else
                        {
                          // false
                        }
                        

                        but his is heavy processing, so it mith be slower that the for loop codito ergo sum

                        1 Reply Last reply
                        0
                        • D Divyang Mithaiwala

                          Hello RichardS, Try this one.

                          double val = 0.0;
                          val = log10(y) / log10(2.0);
                          
                          //Check that 'val' is pure int (Here you use ur own code is u optimize)
                          int val2 = int(val);
                          
                          if (val == val2) 
                               // y is power of 2
                          else
                               // y is not power of 2
                          

                          here 'y' is value u want to check for power of 2. Best of luck


                          Divyang Mithaiwala System Engineer & Software Developer

                          D Offline
                          D Offline
                          Divyang Mithaiwala
                          wrote on last edited by
                          #12

                          Here logic is simple y = value that want to check x = find a value that is in power of 2 so,

                          2^x = y
                          log 2^x = log y
                          x log 2 = log y

                          x = log y /log 2


                          Divyang Mithaiwala System Engineer & Software Developer

                          1 Reply Last reply
                          0
                          • R RichardS

                            Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

                            T Offline
                            T Offline
                            Taka Muraoka
                            wrote on last edited by
                            #13

                            Define "fast". If you're using 32-bit int's, there are only 32 possibilities so you can just check entries in a lookup table, making sure you do the most likely candidates first. BTW, all these suggestions to use sqrt() and log() are nuts - these functions are insanely slow!


                            The two most common elements in the universe are Hydrogen and stupidity. - Harlan Ellison Awasu 2.2 [^]: A free RSS/Atom feed reader with support for Code Project.

                            R 1 Reply Last reply
                            0
                            • R RichardS

                              Hi All, Is there a fast way of checking to see if an int is a power of 2 (i.e. 2, 4, 8, 16, 1024)? I know the long way using a loop, but I was hoping for a simple way of doing this. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

                              R Offline
                              R Offline
                              Ryan Binns
                              wrote on last edited by
                              #14

                              Crikey. I thought this was well known. Just do this:

                              if (x & (x-1))
                              {
                                // x is <edit>not</edit>a power of two
                              }
                              else
                              {
                                // x is <edit>not</edit> a power of two
                              }

                              sorry, got the two cases round the wrong way... :-O

                              Ryan

                              "Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"

                              -- modified at 6:04 Monday 6th March, 2006

                              S N R 3 Replies Last reply
                              0
                              • R RichardS

                                Yip, this was my way to begin with. regards, Rich "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far the Universe is winning." -- Rich Cook

                                R Offline
                                R Offline
                                Russell
                                wrote on last edited by
                                #15

                                Read this function, it could be another start point! This function that I wrote last year find the bigger long, greater than the input value, that is a power of 2. And it is quite fast!:) unsigned long Next2Power(unsigned long x){ unsigned long y=1, x1=x; if(x==0) return 0; while(x1!=0){ x1>>=1; y<<=1; } y>>=1; if(y!=x) y<<=1; return y; }

                                Have a nice code day ;)

                                D 1 Reply Last reply
                                0
                                • R Ryan Binns

                                  Crikey. I thought this was well known. Just do this:

                                  if (x & (x-1))
                                  {
                                    // x is <edit>not</edit>a power of two
                                  }
                                  else
                                  {
                                    // x is <edit>not</edit> a power of two
                                  }

                                  sorry, got the two cases round the wrong way... :-O

                                  Ryan

                                  "Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"

                                  -- modified at 6:04 Monday 6th March, 2006

                                  S Offline
                                  S Offline
                                  Stephen Hewitt
                                  wrote on last edited by
                                  #16

                                  This is by far the best suggestion so far - I'd wager it's impossible to beat this technique. Steve

                                  R 1 Reply Last reply
                                  0
                                  • T Taka Muraoka

                                    Define "fast". If you're using 32-bit int's, there are only 32 possibilities so you can just check entries in a lookup table, making sure you do the most likely candidates first. BTW, all these suggestions to use sqrt() and log() are nuts - these functions are insanely slow!


                                    The two most common elements in the universe are Hydrogen and stupidity. - Harlan Ellison Awasu 2.2 [^]: A free RSS/Atom feed reader with support for Code Project.

                                    R Offline
                                    R Offline
                                    Ryan Binns
                                    wrote on last edited by
                                    #17

                                    Taka Muraoka wrote:

                                    BTW, all these suggestions to use sqrt() and log() are nuts - these functions are insanely slow!

                                    Agreed!! It is quite simple. A single decrement and bitwise AND will do the job nicely

                                    Ryan

                                    "Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"

                                    1 Reply Last reply
                                    0
                                    • R Ryan Binns

                                      Crikey. I thought this was well known. Just do this:

                                      if (x & (x-1))
                                      {
                                        // x is <edit>not</edit>a power of two
                                      }
                                      else
                                      {
                                        // x is <edit>not</edit> a power of two
                                      }

                                      sorry, got the two cases round the wrong way... :-O

                                      Ryan

                                      "Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"

                                      -- modified at 6:04 Monday 6th March, 2006

                                      N Offline
                                      N Offline
                                      Nibu babu thomas
                                      wrote on last edited by
                                      #18

                                      Great work! You've implemented Russel's idea!


                                      Nibu thomas Software Developer

                                      R 1 Reply Last reply
                                      0
                                      • S Stephen Hewitt

                                        This is by far the best suggestion so far - I'd wager it's impossible to beat this technique. Steve

                                        R Offline
                                        R Offline
                                        Ryan Binns
                                        wrote on last edited by
                                        #19

                                        And yet it got the lowest votes of all of them. Funny, isn't it :)

                                        Ryan

                                        "Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"

                                        S 1 Reply Last reply
                                        0
                                        • N Nibu babu thomas

                                          Great work! You've implemented Russel's idea!


                                          Nibu thomas Software Developer

                                          R Offline
                                          R Offline
                                          Ryan Binns
                                          wrote on last edited by
                                          #20

                                          Actually, I've been using this for years doing embedded programming. Every clock cycle is precious ;)

                                          Ryan

                                          "Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"

                                          N R 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups