# Absolute Value Function

• 05-29-2007
Govalant
Absolute Value Function
Hi, the other day I saw an "exercise" of C.

It was:

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?
• 05-29-2007
MacGyver
Yes.

Hint: Down deep under the hood, to a computer, what makes a number negative or positive?
• 05-29-2007
Govalant
I know, the firts bit.

But i tried.

What i do is:

Code:

``` x = (~x) +1;```
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:

Code:

`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
• 05-29-2007
MacGyver
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.
• 05-29-2007
Govalant
omg it's working
Thanks

source:

Code:

```inline unsigned int aabs(int x) {     unsigned int a;     a=x;     return (a ^ (0xFFFFFFFF * (a>>31))) + (a>>31); }```
• 05-30-2007
OS_Hacker
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.

Code:

```              int i;                             i = ( ( i < 0 ) ? ( -1 * i ) : ( i ) );```
• 05-30-2007
vart
Quote:

Originally Posted by OS_Hacker
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.

Code:

```              int i;                             i = ( ( i < 0 ) ? ( -1 * i ) : ( i ) );```

No if
No ?:
No asm
• 05-30-2007
OS_Hacker
Oh i missed that (?:) in the question
... well u definately need to use the bit magic .....
• 05-30-2007
Salem
And if your machines representation of negative numbers isn't 2's complement, you're hosed anyway.
• 05-30-2007
movl0x1
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
or unsigned.

:)