# Absolute Value Function

This is a discussion on Absolute Value Function within the C Programming forums, part of the General Programming Boards category; Hi, the other day I saw an "exercise" of C. It was: Write an absolute value function for an int, ...

1. ## 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?

2. Yes.

Hint: Down deep under the hood, to a computer, what makes a number negative or positive?

3. 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

4. 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.

5. 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);
}```

6. 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 ) );```

7. 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 ) );```
Have you read the OP?
No if
No ?:
No asm

8. Oh i missed that (? in the question
... well u definately need to use the bit magic .....

9. And if your machines representation of negative numbers isn't 2's complement, you're hosed anyway.

10. 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.

Popular pages Recent additions