Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do it without explicit <code>if</code> by using <code>?:</code> as shown by another poster or by using interesting properties of <code>abs()</code> which lets you compute the maximum or minimum of two values.</p> <p>For example, the expression <code>(a + abs(a))/2</code> returns <code>a</code> for positive numbers and <code>0</code> otherwise (maximum of <code>a</code> and <code>0</code>).</p> <p>This gives</p> <pre><code>unsigned char clip(short value) { short a = (value + abs(value)) / 2; return (a + 255 - abs(a - 255)) / 2; } </code></pre> <p>To convince yourself that this works, here is a test program:</p> <pre><code>#include &lt;stdio.h&gt; unsigned char clip(short value) { short a = (value + abs(value)) / 2; return (a + 255 - abs(a - 255)) / 2; } void test(short value) { printf("clip(%d) = %d\n", value, clip(value)); } int main() { test(0); test(10); test(-10); test(255); test(265); return 0; } </code></pre> <p>When run, this prints</p> <pre><code>clip(0) = 0 clip(10) = 10 clip(-10) = 0 clip(255) = 255 clip(265) = 255 </code></pre> <p>Of course, one may argue that there is probably a test in <code>abs()</code>, but <code>gcc -O3</code> for example compiles it linearly:</p> <pre><code>clip: movswl %di, %edi movl %edi, %edx sarl $31, %edx movl %edx, %eax xorl %edi, %eax subl %edx, %eax addl %edi, %eax movl %eax, %edx shrl $31, %edx addl %eax, %edx sarl %edx movswl %dx, %edx leal 255(%rdx), %eax subl $255, %edx movl %edx, %ecx sarl $31, %ecx xorl %ecx, %edx subl %ecx, %edx subl %edx, %eax movl %eax, %edx shrl $31, %edx addl %edx, %eax sarl %eax ret </code></pre> <p>But note that this will be much more inefficient than your original function, which compiles as:</p> <pre><code>clip: xorl %eax, %eax testw %di, %di js .L1 movl $-1, %eax cmpw $255, %di cmovle %edi, %eax .L1: rep ret </code></pre> <p>But at least it answers your question :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload