9

I am converting SIMD code into equivalent c code. I am stuck at one of SSE instructions

__m128i _mm_packus_epi16 (__m128i a, __m128i b)

it returns

r0 := UnsignedSaturate(a0)
r1 := UnsignedSaturate(a1)

...
r7 := UnsignedSaturate(a7)
r8 := UnsignedSaturate(b0)
r9 := UnsignedSaturate(b1)
...
r15 := UnsignedSaturate(b7)

What does UnsignedSaturate mean?

3 Answers 3

18

Basically, "saturation" means that values beyond some "max" value get set to "max", and values below a "min" value get set to "min". Usually, "min" and "max" are the values appropiate for some data type.

Thus, for example, if you take arithmetic on unsigned bytes, "128+128" would have to be "256" (which is hex 0x100), which doesn't fit into a byte. Normal integer arithmetic would create an overflow and discard the part that doesn't fit, which means "128+128 -> 0". With saturated arithmetic, "256 > 255" so the result is 255.

Another option would be scaling, which basically "compresses" the values to a smaller range. Saturation just cuts them off.

You can also use this to put larger types into smaller ones, like putting 16 bit values into 8 bit values. Your example most likely does exactly that, although you'll probably know better than I do what kind of types you are dealing with there.

"UnsignedSaturation" most likely has a min of "0" and a "max" of whatever the max of the result type is. Thus, negative inputs get turned into "0".

4

The instruction converts 16-bit signed integers to 8-bit unsigned integers. The problem is what to do when the value doesn't fit. In other words is less than 0 or larger than 255. Unsigned saturation specifies that the value is then clipped to its range. In other words, values less than 0 are converted to 0, more than 255 to 255.

1
  • Is there an equivalent in C (Not Intrinsics) for this operation? As regular casting won't do that (It won't saturate to zero negative values).
    – Royi
    Apr 26, 2019 at 8:29
2

Saturate simply means that the given variable keeps the maximum possible value instead of overflowing.

unsigned short v1 = 65535;
unsigned (saturate) short v2 = 65535;

v1++;
v2++;
printf("v1=%u v2=%u\n", v1, v2);

prints v1=0 v2=65535

The concept of saturates does not exist in standard C and must be provided by extensions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.