How to rewrite union code in glsl?

I have this code from C++:

float sqrt3(const float x)  
{
  union
  {
    int i;
    float x;
  } u;
  u.x = x;
  u.i = (1<<29) + (u.i >> 1) - (1<<22); 
  return u.x;
} 

I tried to write it in glsl in this manner:

float sqrt3(float x) 
{
 int i = floatBitsToInt(x)&1111;
 i = (1<<29) + (i >> 1) - (1<<22); 
 i=i&floatBitsToInt(x);
 return intBitsToFloat(i);
} 

But, I am getting a black image as output.

int i = floatBitsToInt(x);
i = (1<<29) + (i >> 1) - (1<<22); // = (i>>1) + 0x1fc00000
return intBitsToFloat(i);

It should be noted that this is not technically legal C++. Compilers generally will allow it, but it’s not legal according to the C++ standard, since you’re accessing a union member that is not active.

C++20 got its own “BitsTo” function in std::bit_cast, which can convert the bits of any trivially copyable object to those of another trivially copyable object of the same size.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.