# ABS() function implementation

Discussion in 'C' started by sandeepchiks, Feb 8, 2008.

1. ### sandeepchiksNew Member

Joined:
Feb 8, 2008
Messages:
1
0
Trophy Points:
0
Hi,

How can I write a code for ABS() function, without any condtion check?

Usually ABSOLUTE function is implemented as
int abs(int var)
{
if ( var < 0)
var = -var;
return var;
}

I do not want to have any conditional statement.

Thanks
Sandeep

Joined:
Jul 12, 2004
Messages:
15,296
366
Trophy Points:
83
Type cast it to unsigned int and then return the value

3. ### aperisicNew Member

Joined:
Feb 11, 2008
Messages:
4
0
Trophy Points:
0
You can disguise but you can't easily remove if statement since the extraction from an integer is different if the number is positive or negative. This is one of the solutions that basically says: if number is negative do a bit-inversion after subtracting 1 from it, otherwise do nothing.
Code:
```int my_abs(int x)
{
int t = (unsigned int)x >> 31;
// t is 1 if x is negative
//otherwise it is 0

return (- t) ^ (x - t);
// ^ is XOR and in if t is 1, - 1 will
//create 32 1's to invert x-1,
//otherwise x will not change
}```
or equally,
Code:
```int my_abs(int x)
{
int t = x >> 31;
// t is -1 if x is negative otherwise it is 0

return t ^ (x + t);
}```

Last edited by a moderator: Feb 12, 2008
4. ### aperisicNew Member

Joined:
Feb 11, 2008
Messages:
4
0
Trophy Points:
0
Of course we can create a template to get absolute value from any type of integers:
Code:
```#define BYTE_SIZE 8
[COLOR=RoyalBlue]template [/COLOR] <[COLOR=RoyalBlue]typename [/COLOR] T>
T mabs(T x)
{
T t = x >> ([COLOR=RoyalBlue]sizeof[/COLOR](T)*BYTE_SIZE - 1);
[COLOR=RoyalBlue]return [/COLOR] t ^ (x + t);
}```
usage
Code:
`[COLOR=RoyalBlue]long int[/COLOR] z = mabs<[COLOR=RoyalBlue]long int[/COLOR]>(-11547);`
Now, it looks funny since it seems as if this can be used to get "absolute" value of any structure or class. It may but only if >> is defined. For example >> is not defined for double and float.