round to the nearest power of 4

Discussion in 'C Programming' started by naren2345@yahoo.com, Jan 29, 2007.

  1. Guest

    Would this expression round an integer n to the nearest power of 4 ?

    ((n-1)|3) + 1
    , Jan 29, 2007
    #1
    1. Advertising

  2. wrote:
    > Would this expression round an integer n to the nearest power of 4 ?
    >
    > ((n-1)|3) + 1


    No. Just try it with some simple numbers (1 through 10), then you'll
    get an idea of what it's supposed to do (but doesn't always get right).
    =?utf-8?B?SGFyYWxkIHZhbiBExLNr?=, Jan 29, 2007
    #2
    1. Advertising

  3. Bob Martin Guest

    in 716941 20070129 062444 wrote:
    >Would this expression round an integer n to the nearest power of 4 ?
    >
    >((n-1)|3) + 1


    add 3 then lose 2 low-order bits by shifting (note my assembler background?)
    Bob Martin, Jan 29, 2007
    #3
  4. Richard Bos Guest

    wrote:

    > Would this expression round an integer n to the nearest power of 4 ?
    >
    > ((n-1)|3) + 1


    No, it rounds to something-else of 4.

    Also, for powers, define "nearest": arithmetically, geometrically, or
    unusually?

    Richard
    Richard Bos, Jan 29, 2007
    #4
  5. <> wrote in message
    news:...
    >
    > Would this expression round an integer n to the nearest power of 4 ?
    >
    > ((n-1)|3) + 1


    You need to define what you mean by "power" and by "round" and by "nearest".

    Did you actually mean "multiple" (0, 4, 8, 12, 16, etc.)?

    Or did you actually mean "power" (1, 4, 16, 64, etc.)?

    Looking at your code ...

    0 --> 0
    1 --> 4
    2 --> 4
    3 --> 4
    4 --> 4
    5 --> 8
    6 --> 8

    So in some sense it does round to a near muliple (not power!) of 4. But not
    the nearest one.

    There are an endless variety of code constructs, depending on how efficient
    one needs to be. Certainly

    switch (n & 3)

    comes to mind as a starting point.

    Dave.

    --
    David T. Ashley ()
    http://www.e3ft.com (Consulting Home Page)
    http://www.dtashley.com (Personal Home Page)
    http://gpl.e3ft.com (GPL Publications and Projects)
    David T. Ashley, Jan 29, 2007
    #5
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steve
    Replies:
    5
    Views:
    42,695
    Steve
    May 17, 2004
  2. Fred
    Replies:
    3
    Views:
    63,526
  3. tertius

    round() to nearest .05 ?

    tertius, Nov 15, 2004, in forum: Python
    Replies:
    4
    Views:
    778
    tertius
    Nov 16, 2004
  4. Don
    Replies:
    30
    Views:
    6,262
    murari garg
    Mar 4, 2007
  5. Replies:
    4
    Views:
    494
Loading...

Share This Page