Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Explicit Casts

Standard type casts for the built-in scalar data types defined in Table 4.1 will perform appropriate conversion (except void and half 4). In the next example, f stores 0x3F800000 and i stores 0x1, which is the floating-point value 1.0f in f converted to an integer value:

float f = 1.0f;
int   i = (int)f;

Explicit casts between vector types are not legal. The following examples will generate a compilation error:

int4   i;
uint4  u = (uint4)i;    // compile error

float4 f;
int4   i = (int4)f;     // compile error

float4 f;
int8   i = (int8)f;     // compile error

Scalar to vector conversions are performed by casting the scalar to the desired vector data type. Type casting will also perform the appropriate arithmetic conversion. Conversions to built-in integer vector types are performed with the round-toward-zero rounding mode. Conversions to built-in floating-point vector types are performed with the round-to-nearest rounding mode. When casting a bool to a vector integer data type, the vector components will be set to -1 (that is, all bits are set) if the bool value is true and 0 otherwise.

Here are some examples of explicit casts:

float4 f = 1.0f;
float4 va = (float4)f;  // va is a float4 vector
                        // with elements ( f, f, f, f )

uchar u = 0xFF;
float4 vb = (float4)u;  // vb is a float4 vector with elements
                        // ( (float)u, (float)u,
                        //   (float)u, (float)u )

float f = 2.0f;
int2 vc = (int2)f;      // vc is an int2 vector with elements
                        // ( (int)f, (int)f )
uchar4 vtrue =(uchar4)true;  // vtrue is a uchar4 vector with
                             // elements(0xFF, 0xFF, 0xFF, 0xFF)
  • + Share This
  • 🔖 Save To Your Account