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


Groups > comp.programming > #2367

bit trick

Newsgroups comp.programming
Date 2012-10-19 15:05 -0700
Message-ID <9b4b2014-3882-4d9f-bc89-0adcb3ffc882@googlegroups.com> (permalink)
Subject bit trick
From bob <bob@coolfone.comze.com>

Show all headers | View raw


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?

Back to comp.programming | Previous | Next — 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