Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.programming > #2369

Re: bit trick

From "Charles Richmond" <numerist@aquaporin4.com>
Newsgroups comp.programming
Subject Re: bit trick
Date 2012-10-19 17:34 -0500
Organization A noiseless patient Spider
Message-ID <k5skim$tuc$1@dont-email.me> (permalink)
References <9b4b2014-3882-4d9f-bc89-0adcb3ffc882@googlegroups.com>

Show all headers | View raw


"bob" <bob@coolfone.comze.com> wrote in message 
news:9b4b2014-3882-4d9f-bc89-0adcb3ffc882@googlegroups.com...
>I found this function lying around some code:
>
>    /**
>     * Find the smallest power of two >= the input value.
>     * (Doesn't work for negative numbers.)
>     */
>    private int roundUpPower2(int x) {
>        x = x - 1;
>        x = x | (x >> 1);
>        x = x | (x >> 2);
>        x = x | (x >> 4);
>        x = x | (x >> 8);
>        x = x | (x >>16);
>        return x + 1;
>    }
>
> Can someone explain in layman's terms how that thing works?

It works something like this:

private int roundUpPower2(int x) {
   x -= 1;

   for(int i = 1 ; i  < 17;  i <<= 1)
       x |= x >> i;

   return  x + 1;
   }

--

numerist at aquaporin4 dot com

Back to comp.programming | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

bit trick bob <bob@coolfone.comze.com> - 2012-10-19 15:05 -0700
  Re: bit trick "Charles Richmond" <numerist@aquaporin4.com> - 2012-10-19 17:34 -0500
    Re: bit trick bob <bob@coolfone.comze.com> - 2012-10-22 12:44 -0700
  Re: bit trick Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-10-20 01:46 +0100
    Re: bit trick Robin Vowels <robin.vowels@gmail.com> - 2012-10-20 08:18 -0700
      Re: bit trick Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-10-20 21:08 +0100
    Re: bit trick pete <pfiland@mindspring.com> - 2012-10-20 15:34 -0400
  Re: bit trick Pascal J. Bourguignon <pjb@informatimago.com> - 2012-10-25 13:04 +0000
  Re: bit trick Jongware <jongware@no-spam.plz> - 2012-10-25 16:28 +0200

csiph-web