Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get absolute value without using abs function nor if statement

I was thinking how to get the absolute value of an integer without using if statement nor abs(). At first I was using shift bits left (<<), trying to get negative sign out of the range, then shift bits right back to where it be, but unfortunately it doesn't work for me. Please let me know why it isn't working and other alternatives ways to do it.

like image 681
shanwu Avatar asked Mar 19 '12 14:03

shanwu


1 Answers

From Bit Twiddling Hacks:

int v;           // we want to find the absolute value of v unsigned int r;  // the result goes here  int const mask = v >> sizeof(int) * CHAR_BIT - 1;  r = (v + mask) ^ mask; 
like image 147
Hasturkun Avatar answered Sep 19 '22 16:09

Hasturkun