445,743 Members | 1,122 Online
Need help? Post your question and get tips & solutions from a community of 445,743 IT Pros & Developers. It's quick & easy.

# round to the nearest power of 4

 P: n/a Would this expression round an integer n to the nearest power of 4 ? ((n-1)|3) + 1 Jan 29 '07 #1
4 Replies

 P: n/a naren2...@yahoo.com 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). Jan 29 '07 #2

 P: n/a in 716941 20070129 062444 na*******@yahoo.com 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?) Jan 29 '07 #3

 P: n/a na*******@yahoo.com 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 Jan 29 '07 #4

 P: n/a 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 (dt*@e3ft.com) http://www.e3ft.com (Consulting Home Page) http://www.dtashley.com (Personal Home Page) http://gpl.e3ft.com (GPL Publications and Projects) Jan 29 '07 #5

### This discussion thread is closed

Replies have been disabled for this discussion.