Calculate abs(int) without branching

For this you need someone to teach it to you: if you made it yourself, then you are a very good Comp-Sci, and you should send your CV to Google ASAP. ;) Without branching O_o? Yes, without using any “if ( a < 0 )…”. To do that, you need to refresh how Two’s Complement works, then come back. What we really need to focus on is that, given a signed int A, the negative of that number is: B = ~A + 1. BUT, we are trying to calculate the Absolute Value, not the negative. So, something like: ...

January 13, 2010 · 3 min · 433 words

Swap the value of two integers without temporary storage

Someone says this is an old lame trick. I think it’s simple and clever use of XOR. How/Why does it work? It’s built around the properties of the XOR ^ operator, who has the following properties: A ^ B = B ^ A (commutative) A ^ 0 = A A ^ 1 = ~A A ^ A = 0 So, you can see how it get’s applied here: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <stdio .h> int main(void) { unsigned int a, b; // ... populate somehow "a" and "b"... printf("a = %d - b = %d\n", a, b); a ^= b; // store in "a" the value of "a XOR b" b ^= a; // store in "b" the value of "a XOR b XOR b" = "a XOR 0" = "a" a ^= b; // store in "a" the velue of "a XOR b XOR a" = "b XOR 0" = "b" printf("a = %d - b = %d\n", a, b); } Neat.

January 13, 2010 · 1 min · 174 words