[fpc-pascal] two small ?s - high(real) and nearest 2^x

Schatzl Thomas tom_at_work at gmx.at
Sun Oct 11 12:17:55 CEST 2009


Hello,

> 2. For the purposes of reserving memory in block sizes that can be 
> easily reallocated, I like to use powers of two. So if I have, e.g., a 
> dynamic array, I might start with a size of 1024 and then double it 
> when it hits capacity. Hopefully this smoothes memory management, as I 
> am using a lot of memory...
> 
> Anyway, what I'd like is a simple function that can quickly identify the 
> next power-of-two larger than an arbitrary number. So if I feed the 
> function 472, it will return 512. Thus far I haven't been able to 
> figure out how to do this without a big if-then-else nest. Is there 
> some clever way to request that the processor return the position of 
> the leftmost '1' in 00101101?

Solutions with loops have already been posted, here one without any for completeness:

function next_power_of_2(v : dword) : dword;
begin
  // make sure that x <= 2^31 and x <> 0
  dec(v);
  v := v or (v >> 1);
  v := v or (v >> 2);
  v := v or (v >> 4);
  v := v or (v >> 8);
  v := v or (v >> 16);
  inc(v);
  result := v;
end;

Explanation: http://bits.stephan-brumme.com/roundUpToNextPowerOfTwo.html

Hth,
  Thomas

-- 
Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 -
sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser



More information about the fpc-pascal mailing list