Compute the integer absolute value (abs) without branching | GeeksforGeeks
mask = n>>31
For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers.
Read full article from Compute the integer absolute value (abs) without branching | GeeksforGeeksmask = n>>31
For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers.
unsigned
int
getAbs(
int
n)
{
int
const
mask = n >> (
sizeof
(
int
) * CHAR_BIT - 1);
return
((n ^ mask) - mask);
}
unsigned
int
getAbs(
int
n)
{
int
const
mask = n >> (
sizeof
(
int
) * CHAR_BIT - 1);
return
((n + mask) ^ mask);
}