Velocity Reviews > round to the nearest power of 4

# round to the nearest power of 4

naren2345@yahoo.com
Guest
Posts: n/a

 01-29-2007

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

((n-1)|3) + 1

=?utf-8?B?SGFyYWxkIHZhbiBExLNr?=
Guest
Posts: n/a

 01-29-2007
(E-Mail Removed) 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).

Bob Martin
Guest
Posts: n/a

 01-29-2007
in 716941 20070129 062444 http://www.velocityreviews.com/forums/(E-Mail Removed) 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?)

Richard Bos
Guest
Posts: n/a

 01-29-2007
(E-Mail Removed) 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

David T. Ashley
Guest
Posts: n/a

 01-29-2007
<(E-Mail Removed)> wrote in message
news:(E-Mail Removed) oups.com...
>
> 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.)?

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 ((E-Mail Removed))
http://gpl.e3ft.com (GPL Publications and Projects)