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

Anton Tichawa anton.tichawa at chello.at
Sat Oct 10 19:40:13 CEST 2009


On Sat, 2009-10-10 at 10:14 -0700, David Emerson wrote:
> 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?

On the processor level, if it is an x86, you can use "bsr" (bit scan
reverse). Other processors may have similar instructions. I don't know
if this is somehow mapped to an RTL function.

In pure pascal, use a loop to determine the magnitude, something like
(omitting the details):

  repeat
    requested := requested shr 1;
    inc(magnitude);
  until requested=0;

Anton





More information about the fpc-pascal mailing list