Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

CUDA: Reinterpret variable of one type as of another type

📅 2012-Jun-07 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cuda, reinterpretation, type ⬩ 📚 Archive

Sometimes, it might be useful to reinterpret the bits of a variable of one type as if it were of another type. Note that this is completely different from converting or casting a variable of one type to another type.

Such a reinterpretation is frequently employed between floating-point and integer types. The union construct or pointer casting can be used to achieve such reinterpretation.

An alternative is to use the intrinsic functions in CUDA. The intrinsic functions related to reinterpretation can be found listed in the CUDA Reference Manual under the Type Casting Intrinsics section. For example, the intrinsic function to reinterpret float as int is __float_as_int()

// 1. Using union
__device__ int floatAsInt( float fval )
    union FloatInt {
        float f;
        int   i;

    FloatInt fi;
    fi.f = fval;
    return fi.i;

// 2. Using pointer
ival = *( ( int* ) &fval );

// 3. Using CUDA intrinsic function
ival = __float_as_int( fval );

Tried with: CUDA 4.2

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧