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.)?

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

 Thread Tools

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post lilmax88@gmail.com C++ 4 04-05-2007 01:25 AM Don Java 30 03-04-2007 08:23 AM tertius Python 4 11-16-2004 10:58 AM Fred Java 3 06-06-2004 06:20 AM Steve Java 5 05-17-2004 01:30 AM

Advertisments