Search code examples
d

Type punning in D


I'm attempting to translate the infamous fast inverse square root technique to the D programming language from C. A necessary step involves storing long bits in an integer:

i  = * ( long * ) &y; 

In the comments section, Andrew suggests that this operation is called type punning. Does anyone know how to perform a type pun operation in D?

For those who are curious, here's a complete C representation of the code:

float Q_rsqrt( float number ) {
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y  = number;
i  = * ( long * ) &y;    // the part in question
i  = 0x5f3759df - ( i >> 1 );
y  = * ( float * ) &i;   // again, but for floating points
y  = y * ( threehalfs - ( x2 * y * y ) );
return y;
}

Solution

  • All you really needed to do was to use the D-style casting - that is the only place where D code differs from the C one.

    Here is the working program:

    import std.stdio;
    
    float Q_rsqrt(float number) {
      int i;  // we use int here because int.sizeof == float.sizeof
      float x2, y;
      const float threehalfs = 1.5F;
      x2 = number * 0.5F;
      y  = number;
      i  = * cast(int*) &y;
      i  = 0x5f3759df - ( i >> 1 );
      y  = * cast(float*) &i;
      y  = y * ( threehalfs - ( x2 * y * y ) );
      y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration
    
      return y;
    }
    
    int main() {
      writeln(Q_rsqrt(0.15625f));
      // Output: 2.52981
    
      return 0;
    }