OpenCL中的向量数据类型转换

OpenCL中的向量数据类型转换

1.函数原型

convert_destType(sourceType)
destType convert_destType<_sat>(sourceType)
destTypen convert_destTypen<_sat>(sourceType)

2.适用场景

  • convert_destype(sourceType)
    支持int float uchar等常见内建数据类型以及bool,half,size_t,ptrdiff_t,intptr_t,uintptr_t 和void等等.
  • 饱和(溢出)处理
    convert_destype(sourceType)函数不会对数据做溢出处理,例如float转uchar的时候,会出现溢出,导致数据错误.
    _sat是溢出处理选项,例如int转uchar,当数据大于uchar_max,这取255,小于0,则取0;
    roundingMode是舍入处理模式(浮点数转整数),主要包含一下几种:
    _rte : 四舍五入(如果舍入为中间值,即舍还是入距离相等,那么按其最末尾一位是奇数,则入,如果为偶数,则舍)
    _rtz : 向0方向舍入
    _rtp : 向正无穷方向舍入
    _rtn : 向负无穷方向舍入
    默认 :若转为整数,使用_rtz;若转为浮点数使用_rte
  • 注意
    数据类型转换要求输入与输出元素个数相同

3.Example

uchar4->int4

uchar4 u;
int4   c = convert_int4(u);

float->int

float   f;
int    i = convert_int(f);

饱和处理的例子

short4  s;

// negative values clamped to 0
ushort4 u = convert_ushort4_sat( s );

// values > CHAR_MAX converted to CHAR_MAX
// values < CHAR_MIN converted to CHAR_MIN
char4 c = convert_char4_sat( s );
float4 f;

// values implementation defined for
// f > INT_MAX, f < INT_MIN or NaN
int4   i = convert_int4( f );

// values > INT_MAX clamp to INT_MAX, values < INT_MIN clamp
// to INT_MIN. NaN should produce 0.

// The _rtz rounding mode is
// used to produce the integer values.
int4   i2 = convert_int4_sat( f );

// similar to convert_int4, except that
// floating-point values are rounded to the nearest
// integer instead of truncated
int4   i3 = convert_int4_rte( f );

// similar to convert_int4_sat, except that
// floating-point values are rounded to the
// nearest integer instead of truncated
int4   i4 = convert_int4_sat_rte( f );
int4   i;

// convert ints to floats using the default rounding mode.
float4 f = convert_float4( i );

// convert ints to floats. integer values that cannot
// be exactly represented as floats should round up to the
// next representable float.
float4 f = convert_float4_rtp( i );      

OpenCL中的向量数据类型转换_第1张图片

欢迎扫码关注公众号:计算机视觉与高性能计算(微信号:to_2know)

参考资料
khronos.org

你可能感兴趣的:(OpenCL并行计算实验之路)