Absolute Value Function
Hi, the other day I saw an "exercise" of C.
Write an absolute value function for an int, that doesn't use if, ?:, asm or calls to other functions.
It's been two weeks since i'm trying to do it but i can't find a way.
Does anyone know how to do it?
Hint: Down deep under the hood, to a computer, what makes a number negative or positive?
I know, the firts bit.
But i tried.
What i do is:
and that gives me the opposite.
But i need the absolute for all vales, negative or positive. And i can't find a way.
I tried this, it's a bit complicate:
return (x ^ (0xFFFFFFFF * (x>>31))) + (x>>31);
Besides, the first bit is not actually the sign, but rather when the first bit is one you start at the lowest negative value and keep adding the other bits
That's because x is signed. For simplicity, create an unsigned int inside your function, and assign it the value of x.
Your last return value should then work if you perform those operations on the unsigned version of x.
omg it's working
inline unsigned int aabs(int x)
unsigned int a;
return (a ^ (0xFFFFFFFF * (a>>31))) + (a>>31);
if the question says use bit wise operations then u already have a solution. Well if you dont want to use if..else there is another operator called the conditional operator that ?: ... if the question relates to that then this might just be what you looking for.
i = ( ( i < 0 ) ? ( -1 * i ) : ( i ) );
Have you read the OP?
Originally Posted by OS_Hacker
Oh i missed that (?:) in the question
... well u definately need to use the bit magic .....
And if your machines representation of negative numbers isn't 2's complement, you're hosed anyway.
Actually, inside the computer this:
1111 1111 is -1 and
1111 1111 is 255 The way a computer differentiates is by
checking flags in the FLAG register.
Just because there's a HIGH bit in the most significant bit doesn't mean
it's a negative number.
The JA (jump above) and JG (jump if greater) are coded into the compare
instruction depending on if the intent was treating the number as signed