Here is a rather evil way to quickly compute the closest powers of 2 to a number.

First, figure out which bits represent the mantissa in your native floating point format. Then you can zero out all of the bits in the mantissa (which doesn't include the highest bit) and get the closest previous power of 2.

Getting the closest next power of 2 is a bit trickier.

Inspired by a CB question from BrowserUk and my previous (tye)Re: How can I tell if a number is a power of 2?.

Sample output:

0 == 0 == 0 1 <= 1 <= 1 2 <= 2 <= 2 2 <= 3 <= 4 4 <= 4 <= 4 4 <= 5 <= 8 16384 <= 32000 <= 32768 8589934592 <= 10000000000 <= 17179869184 -2 >= -2 >= -2 -2 >= -3 >= -4 0.0625 <= .1 <= 0.125 0.0078125 <= .01 <= 0.015625 -0.0009765625 >= -.001 >= -0.001953125 5.61779104644474e+306 <= 1e307 <= 1.12355820928895e+307 8.98846567431158e+307 <= 1e308 <= 1.#INF 8.90029543402881e-308 <= 1e-307 <= 1.78005908680576e-307
(updated)

#!/usr/bin/perl -w use strict; my $mant; BEGIN { my $max= 2; $max *= 2 until 2*$max+1 == 2*$max; $mant= pack("d",$max) ^ pack("d",2*$max-1); } sub prevPower2 { my( $n )= @_; return unpack "d", ~$mant & pack "d", $n; } sub nextPower2 { my( $n )= @_; my $p= prevPower2( $n ); $p *= 2 if $p != $n; return $p; } while( <> ) { chomp; my $dir= (qw( < = > ))[ 1 + (0<=>$_) ]; print prevPower2($_), " $dir= $_ $dir= ", nextPower2($_), $/; }

In reply to Next/Prev power of 2 by tye

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.