Find Absolute value (abs) without branching in C ++

Hello Everyone, Hope Everyone’s well. Today is all about finding the absolute value of a number but without branching in C++.

Absolute value (abs) without branching in C ++

Every number in computer stores in a binary format. It can be either a positive or negative number. Negative numbers store in 2’s complement form. We need to interchange the bits of the respective digit for getting the absolute value. As an example, 4 stored as 11111100(2’s complement) and the leftmost bit is for the sign bit. if it’s 1 then it is negative and if it’s 0, then it is positive. To get the absolute value we need to perform 1’s complement i.e 00000011 and then add 1 to it i.e 00000100. (It is an example in an 8bit system)

 

Solution :

It is easier to use the formula ((n+mask)^mask) for masking and consider our system as 32 bit where n>>31. So here we use the trick as for negative numbers we will get all zeros and for positive numbers, we will get all ones.

Now we add the value with our mask to get the actual result.

C++ Code

#include <bits/stdc++.h> 
using namespace std; 



 int abs(int n) 
{ 
  int const mask = n >> (sizeof(int) * 8 - 1); 
  int d = ((n + mask) ^ mask);
  return d;
} 


int main() 
{ 
  int n = -7; 
  cout << "Absolute value of " << n << " is " << abs(n); 
  return 0; 
} 

Output –

 Absolute value of -7 is 7

Leave a Reply

Your email address will not be published. Required fields are marked *