[ create a new paste ] login | about

Link: http://codepad.org/Gc19m7mX    [ raw code | fork | 1 comment ]

AaronMiller - Plain Text, pasted on Mar 8:
Non-branching check for zero (1 if zero, 0 otherwise):

  (a ^ (-a)) >> (sizeof(a)*8 - 1)

If you need an entire mask (e.g., 1111 1111 1111 1111) if zero, then:

  -((a ^ (-a)) >> (sizeof(a)*8 - 1))

That works because:

 1	0000 0000 0000 0001
-1	1111 1111 1111 1111

and

 0	0000 0000 0000 0000
-0	0000 0000 0000 0000

----------------------------------------------------------------------

Scratch/Test Numbers

 38756	1001 0111 0110 0100
-38756	0110 1000 1001 1100
   or	1111 1111 1111 1100

 25000	0110 0001 1010 1000
-25000	1001 1110 0101 1000
   or	1111 1111 1111 1000

 12	0000 0000 0000 1100
-12	1111 1111 1111 0100
   or   1111 1111 1111 1100

 0	0000 0000 0000 0000
-0	0000 0000 0000 0000
   or	0000 0000 0000 0000

 1	0000 0000 0000 0001
-1	1111 1111 1111 1111



Create a new paste based on this one


Comments:
posted by AaronMiller on Mar 8
The reason this allows for non-branching code is because you can take the result of "-((a ^ (-a)) >> (sizeof(a)*8 - 1))" and use that as a mask, as shown in my previous non-branching code entry (http://codepad.org/a8uewrxX).
reply