Tuesday, March 29, 2005
More on bit
http://www.ee.surrey.ac.uk/Personal/D.Carey/teaching/cs154/Lectures1-4.ppt#257,1,Slide
1. How to implement conditional operator ? without if...then...else, only use ~,!,&,^,+
x?y:z when x==0 return z else return y
suppose x?y:z equals
y=f(x) + z&g(x)
then
when x==0 f(x)=0,g(x)=-1 (0xffffffffffffffff)
else f(x)=-1,g(x)=0
notice that
1. ~o = -1, ~(-1) = 0,
2. !x=1 when x==0,
=0 else
3. -x = ~x + 1
so we have
f(x) = ~(!(!x))+1
g(x) = ~(!x) + 1
Thinking one more step: How would you implement Logical Not (!) without branch
like if...then...else
The trick is x^-x will set the sign bit (Left Most Bit) unless x==0
Assuming value x has N bits, then we have
!x = (((x^-x)>>N-1)&1)^1