Advertisement

higher power of 2 less given float

Started by March 19, 2003 03:29 AM
9 comments, last by minorlogic 21 years, 11 months ago
Is there a fast trip to find it ?
Could you give me an example? I don''t quite see what you want...
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
Advertisement
Are you asking to find the highest power of 2 less than a given float? If so the specification of IEEE floats can help you. I believe they are in the format : m * 2^e where m is the mantissa and e is the exponenent. m is limited in value from 0 to 2^24 - 1 and e ranges from -149 to 104. Therefore finding the highest power of 2 less than m should be all you need. Since m is an integer with a small range, simple lookup tables should suffice or you could find the highest significant bit in m and use that.
int( ln(myFloat) / ln(2) )

Unless someone has a quick assembly routine or other function for log2. Maybe storing the constant 1 / ln(2) elsewhere. Big discussion in a logarithm thread a few days ago. Good read.
That method seems extraordinarily slow to me.

2^n <= f2^n <= m * 2^e2^(n-e) <= m  


Since m is in 0...2^24 - 1, it is easy to find the greatest power of 2 less than it. Just use highest significant bit. This whole procedure can be done in a few operations assuming you can get at the internal float format of Mantissa:Exponent.

[edited by - jermz on March 19, 2003 3:05:24 PM]
Ok ! Let''s talk only about integers

example:
3 -> 2 -> pow 1
9 -> 8 -> pow 3
13 -> 8 -> pow 3
15 -> 8 -> pow 3
16 -> 16 -> pow 4
17 -> 16 -> pow 4

Realy i need the VALUE that is a integer power of 2 and not greater that given INTEGER.

I know how to find it , I NEED a fast solution , if it exist based on bit trips.












Advertisement
You could use the (x86) BSR assembler instruction.
BSR! Thanks Anonymous Poster ! I have been looking for the answer to this question, too.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
Thanks ! BSR is ok !

But may be exist some without asm ?
float MaxPowerOfTwoLessThanOrEqualTo(float a){	int *p;	p = (int *)&a	*p = (*p & 0x7F800000);	return a;}void main(void){	cout << MaxPowerOfTwoLessThan(7.5f) << endl; //4	cout << MaxPowerOfTwoLessThan(8.0f) << endl; //8	cout << MaxPowerOfTwoLessThan(10.0f) << endl; //8} 

If you want max power less than, you should be able to get that by subtracting a small number from A(like 0.01f) before doing the pointer stuff.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk

This topic is closed to new replies.

Advertisement