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:
| |
Does it makes sense to you? To me it didn’t for the first 10 minutes.
What do we need?
We need, given the integer in input, to calculate 2 values:
A way to “optionally negate” the input
A variable carrying
0if the input is positive,1otherwise
Look what we have here: the XOR
Properties of XOR are:
A ^ 0 = AA ^ 1 = ~AA ^ A = 0A ^ B = B ^ A(commutative)
The first two properties are key here: if we could only generate a variable from the input that contains 0 if positive and 1 if negative, we would have half hack done.
Ladies and Gentleman, all shift please
Now, let’s see some shifting in action. If A is a Positive number, then:
| |
While if A is a Negative number, then:
| |
Putting all together
So, this means that we can calculate the absolute value using the new variables we have produced, A and B. Here is how:
| |
Who showed me this hack? eh eh eh! ;)