SPRUI04F july 2015 – april 2023
You cannot use standard type casting on vector data types. Instead, convert_<destination type>(<source type>) functions are provided to convert the elements of one vector type object into another vector type object. This is done on an element-by-element basis, and the source vector type and the destination vector type must be of the same length. That is, 4-element vectors can only be converted to other types of 4-element vectors.
The following example initializes a short2 vector using two ints concatenated to form an int2 vector:
void foo(int a, int b)
{
short2 svec2 = convert_short2((int2)(a, b));
...
}
If the data stored by a vector element is outside the range of values that can be stored in the destination type, by default the value is truncated. However, if you add the _sat modifier (for "saturated") to the function name, values that are outside the range of the destination type are set to the maximum value of the destination type (or minimum for negative values outside the range). The _sat modifier cannot be used when converting an integer vector to a floating-point vector. In the following example, any values larger than 32,767 stored in an element of myint4 are set to as 32,767 in the corresponding element of myshort4.
int4 myint4;
short4 myshort4 = convert_short4_sat( myint4 );
Likewise, when converting between floating-point and integer vectors, one of the following modifiers can be added to the function name to specify how the floating-point values should be rounded:
When converting an integer type to a float, rounding is not necessary. Rounding from a larger float type (double) to a smaller float type (float) does require rounding. The default rounding method for double to float conversions is _rte.
The following example converts the data stored in a float4 to an int4. It uses the _rtp modifier, so values are rounded up toward positive infinity:
float4 myfloat4;
int4 myint4 = convert_int4_rtp( myfloat4 );
The _sat modifier can be combined with a rounding modifier. The following example rounds floating values toward even and sets values greater than the maximum possible short value to the maximum value:
float4 myfloat4;
int4 myshort4 = convert_short4_sat_rte( myfloat4 );
If vector data types are enabled, you can also use the convert_<type>() functions for scalar (non-vector) types such as short and int. The result is the same as type casting the source type. Conversions between scalar types and vector types is not allowed, because the source and destination types must contain the same number of elements.
The convert_<destination type>() functions are not available for use with complex vector types.