# 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

2. ### =?utf-8?B?SGFyYWxkIHZhbiBExLNr?=Guest

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

3. ### Bob MartinGuest

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
4. ### Richard BosGuest

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
5. ### David T. AshleyGuest

<> 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

### 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.