__int_as_float(...)

Im getting this error. obviously i cannot call __float_as_int and __int_as_float from the host… but i need these so that I can use long ints and floats together compressed into float4 structures without data loss. Does anyone have a workaround?

…keep in mind this is not the same thing as (float)myInt .

"simpleGL.cu", line 112: error: calling a __device__ function from a __host__

          function is not allowed

   return __int_as_float(a);

no, we can’t do that. i have a related post before.

As the host code is just like any other C function or C++ method, just cast to the desired data type.

Peter

he’s concerning about precision lost i think, (1:8:)23 bit float vs 32 bit int.

What about this:

#define INT_AS_FLOAT(x) (*((float*)&(x)))

This should do the same as the kernel function, but on the host.

Or do it as the default impl on the device is doing:

__func__(float __int_as_float(int a))

{

  union {int a; float b;} u;

 u.a = a;

 return u.b;

}

Peter

Use the union method Peter posted, not a pointer cast, as the pointer cast breaks C++ strict aliasing rules. I’ve worked with an external piece of software that uses the pointer cast method, and it crashes horribly unless you compile with the gcc flag -fno-strict-aliasing (or compile without optimizations… but that is dumb).

Hm, you’re right, taking the address of a variable is not the best idea. I generally use pointer casts to change the type of arrays, for which they do work.

hey guys u were a great help… that union thing should work great.

Hallo,

I have the same problem: I pack two informations in a single float4 data, that is a threedimensional vector x,y,z of a particle, and its itentifier ‘i’, so that the float4 contains {x,y,z,i}. However, since ‘i’ is integer, I must use __float_as_int and __int_as_float to convert the 4-th component from/to integer.

But these functions are not available on host (where I must ‘prepare’ the buffers with precomputed identifiers) as said in this thread, so I want to use the “union” idea posted above: I will create a function for my int->float storage from the host side…

float __host_int_as_float(int a)

{ 

 union {int a; float b;} u; 

 u.a = a; 

 return u.b; 

}
  • is it guaranteed to work on all compilers?

  • has anyone already tested this idea?

  • what happens if I simply use casting? I mean, if on host I do simply “buffer[n].w=(float)identifier” and viceversa on device I do “identifier=(int)buffer[n].w”. I mean, will it work up to some max. integer number? is it reliable or is there some risk?

thanks,

A.Tasora

Università di Parma