r/ProgrammerTIL • u/mikaey00 • May 16 '19
Other TIL learned how floating-point numbers are represented in binary form.
I'm 37 now, and I've been doing C since I was maybe 14. I never quite understood the binary format of floating point numbers, so finally I sat down and managed to find something that explained it to me. With that, I was able to write the following pseudocode to decode a floating-point number (the example below is for a 32-bit float):
Sign = FloatVal >> 31; // Bit 0
Exponent = ( FloatVal >> 23 ) & 0x7f; // Bits 1-8
Mantissa = FloatVal & 0x7fffff; // Bits 9-31
if( Exponent == 255 ) {
if( Mantissa == 0 ) {
return ( Sign == 1 ? -Infinity : Infinity );
} else {
return ( Sign == 1 ? -NaN : NaN );
}
} else {
if( Exponent != 0 ) {
return ( Sign == 1 ? -1 : 1 ) * ( 1 + ( Mantissa / 0x800000 ) ) * 2^( Exponent - 127 );
} else {
return ( Sign == 1 ? -1 : 1 ) * ( Mantissa / 0x800000 ) * 2^-126;
}
}Thank you to Bruce Dawson's blog that explained this nicely!
164
Upvotes
View all comments
Show parent comment
13
u/WikiTextBot May 17 '19
Fast inverse square root
Fast inverse square root, sometimes referred to as Fast InvSqrt() or by the hexadecimal constant 0x5F3759DF, is an algorithm that estimates 1⁄√x, the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point format. This operation is used in digital signal processing to normalize a vector, i.e., scale it to length 1. For example, computer graphics programs use inverse square roots to compute angles of incidence and reflection for lighting and shading. The algorithm is best known for its implementation in 1999 in the source code of Quake III Arena, a first-person shooter video game that made heavy use of 3D graphics.
[ ^PM | Exclude ^me | Exclude from ^subreddit | FAQ / ^Information | ^Source ] Downvote to remove | v0.28