Variable Casting in OpenCL with as_type

>> Sunday, October 23, 2011

One of my favorite OpenCL tricks involves using the result of a vector comparison as the mask argument of a shuffle/shuffle2 operation. This makes it easy to sort a vector's components in place.

The problem is that vector comparisons produce signed integer vectors and the shuffle functions require their mask vectors to contain unsigned values. OpenCL doesn't tolerate regular C/C++ casting, so you can't use anything like:

shuffle(input, (uint4)mask);
Earlier, I used the abs function to convert signed vectors to unsigned vectors. But OpenCL makes it possible to cast variables properly using the as_type function. Here, type represents the desired data type. An example will show how this works:
shuffle(input, as_uint4(mask));
It works just as simply for scalars as it does for vectors, and it can be used for floating-point as well as signed conversion. For example, to convert a float called x to an int, you'd call as_int(x).


Post a Comment

  © Blogger template Werd by 2009

Back to TOP