Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type punning in D

Tags:

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;
}
like image 585
David Shaked Avatar asked Dec 28 '25 08:12

David Shaked


1 Answers

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;
}
like image 60
DejanLekic Avatar answered Dec 30 '25 22:12

DejanLekic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!