vimwiki/tech/bithacks.wiki

69 lines
1.5 KiB
Plaintext

= Bithacks =
Evil memory manipulation for speed
== Bitwise_cast ==
This works for C/C++. Basically all you do it cast like this
{{{C
float cast(int foo){
return (* (float*)&foo);
}
}}}
This is also known as the "evil floating point bit level hacking" from the
quake III fast inverse square root. Great for casting structs as memory for
hashing, or generally treating one set of bits as another type
== Negating Floats ==
{{{
float Negatefloat(float f){
return cast_float_to_uint(f) ^ 0x80000000;
}
}}}
== Fast log base 2 ==
IEE 754 is sci notification of a base 2 value, therefore this works very very
well. Breaks awfully with negtaives so be sure to check
{{{
const unsigned int OneAsInt = 0x3F800000;
const float ScaleUp = float(0x00800000); //2^23
const float ScaleDown = 1.0f/ScaleUp;
float Log2(float x){
return float (cast_float_to_uint(f)-OneAsInt)*ScaleDown
}
}}}
== Fast base 2 exponent ==
This is the opposite of the last one. Does 2^n fast
{{{
const unsigned int OneAsInt = 0x3F800000;
const float ScaleUp = float(0x00800000); //2^23
const float ScaleDown = 1.0f/ScaleUp;
float Log2(float x){
return asfloat (cast_float_to_uint(f)*ScaleUp)+OneAsInt;
}
}}}
== Not accurate square root ==
This doesnt do that well but its better really fast. Does a fast taking of the
float to the power of 0.5
{{{
const unsigned int OneAsInt = 0x3F800000;
float sqrt(float x){
return asfloat((asint(x)>>1)+(OneAsInt>>1));
}
}}}
[[index]]