get absolute value without using abs function nor if statement

how to find absolute value in java without using math abs
program to find absolute value of a number in c
bitwise absolute value
c absolute value
math h absolute value
abs macro function
c++ abs absolute value
compute absolute value

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.

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;

We need not to do anything if a number is positive. To get the absolute value of a negative number, we have to toggle all bits and add 1 to the toggled number i.e​, 0 0 0 0 0 0 0 1 + 1 will give the This function will return absolute value of n*/. The real/actual magnitude of a number (numerical value) without sign is known as Absolute value. For example - if there is a value -10 its absolute value will be 10, and if the value is 10 its absolute value will also be 10.

int abs(int v) 
{
  return v * ( (v<0) * (-1) + (v>0));
  // simpler: v * ((v>0) - (v<0))   thanks Jens
}

This code multiplies the value of v with -1 or 1 to get abs(v). Hence, inside the parenthesis will be one of -1 or 1.

If v is positive, the expression (v>0) is true and will have the value 1 while (v<0) is false (with a value 0 for false). Hence, when v is positive ((v>0) - (v<0)) = (1-0) = 1. And the whole expression is: v * (1) == v.

If v is negative, the expression (v>0) is false and will have the value 0 while (v<0) is true (value 1). Thus, for negative v, ((v>0) - (v<0)) = (0-1) = -1. And the whole expression is: v * (-1) == -v.

When v == 0, both (v<0) and (v>0) will evaluate to 0, leaving: v * 0 == 0.

Works with integer or decimal numbers of any length. When assigned to a function: take the maximum between the negative and the number, using a reduce the function, but I haven't been able to replicate the input on SO. abs value _ } # if-else statement ^ # pop the TOS without outputting ; # swap the top two stack  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more How do I get the absolute value of an integer without using Math.abs?

Branchless*:

int abs (int n) {
    const int ret[2] = { n, -n };
    return ret [n<0];
}

Note 4.7 Integral Conversions / 4: [...] If the source type is bool, the value false is converted to zero and the value true is converted to one.


*: In the sense that there is no conditional branching in your code. Under the hood, the ternary operator will also produce a branch. However, it's also a valid answer, because the ternary one isn't an if-statement. This doesn't imply that your compiler isn't able to emit branchfree assembly code for code that logically branches.

In the example, the variable value is not changed. Usually, an assignment operator is used to make a change. double value = -34.569; double abs; abs = (​value <  What is the ABSOLUTE Function in Excel (ABS)? The ABSOLUTE function in Excel returns the absolute value of a number. The function converts negative numbers to positive numbers while positive numbers remain unaffected. Formula. ABSOLUTE Value = ABS(number) Where number is the numeric value for which we need to calculate the Absolute value.

Assuming 32 bit signed integers (Java), you can write:

public static int abs(int x)
{
    return (x + (x >> 31)) ^ (x >> 31);
}

No multiplication, no branch.

BTW, return (x ^ (x >> 31)) - (x >> 31); would work as well but it is patented. Yup!

Note: This code may take more then 10x longer then conditional statement (8bit Verison). This may be useful for Hardware programming System C etc

Learn: How to get absolute value of any integer without using abs() function of For example - if there is a value -10 its absolute value will be 10, and if the value is 10 Here, we will not use library function abs(), we are using two methods to get the absolute Here is the statement of Parameterized Macro The challenge is to take any real number as input and output or return the absolute value. You may not use any built-in functions other than those dealing with input and output/returning. This is code golf, so the shortest code wins. This is my first question here, so bear with me if I've left something obvious out of the challenge.

I try this code in C, and it works.

int abs(int n){
   return n*((2*n+1)%2); 
}

Hope this answer will be helpful.

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  / The asker is looking for a way to get the absolute value without the abs family of functions and without using if-statements, not more, not less. Also, relational comparison in itself is not conditional, resulting control may be. And by your style of argumentation: Bitwise is abs as it must produce abs-result, and the whole discussion drowns.

The abs() function takes a single argument and returns a value of type int , long int or long long int . abs() Parameters. x : An integral value whose absolute value is  What I would like is the following; when its a negative value to use the absolute value ie: =IF((4.695-4.891)= -0.196 convert to 0.196 go through the rest of the logic if it stops at the first if then . my result should be a fraction 1/0.196 of absolute or .5.10 and that greater thanC40(SEE REFERENCE TABLE --c40) result should be 9

The absolute value of a negative number is the number without its negative sign. The ABS function in Excel has just one purpose - to get the absolute value of It can be represented by a value, cell reference or another formula. to the allowed tolerance: ABS(A2-B2)<=C2; Use the IF statement to return  So x - 1 XORed with all ones produces -(x - 1) - 1 = -x + 1 - 1 = -x, which is the absolute value of x except when x is the minimum possible value for the format (−2,147,483,648 for 32-bit two’s complement), in which case the absolute value (2,147,483,648) is too large to represent, and the resulting bit pattern is just the original x.

The abs() function is used to get the absolute (positive) value of a given number. The argument may be an integer or a floating point number. If  This is awkward for such a simple idea. The following does the same thing in one statement: abs = (value < 0 ) ?-value : value ; This statement uses a conditional operator. The right side of the = is a conditional expression. The expression is evaluated to produce a value, which is then assigned to the variable, abs.

Comments
  • If you know the size of the int you're dealing with, just use a bit-wise "and" to clear the highest-order bit.
  • @MarcB: That'll work with sign/magnitude representation (which is fairly unusual) but fail miserably for 1's complement or (by far the most common) 2's complement.
  • @MarcB: It's slightly more involved than that for 2's complement.
  • it's not a homework, but a question asked by my compiler course instructor. I found it is an interesting question because I've never done it this way before. By the way, solving this problem won't improve my grade for the course, but it will certainly improve my coding skills. ^__^
  • can someone explain me why ((n < 0) ? (-n) : (n)) or ((n < 0) ? (n * -1) : (n)) is wrong?
  • I think this is the answer the OP was looking for.
  • v >> sizeof(int) * CHAR_BIT - 1 could you please explain what this does?
  • @codeymodey: I didn't write the original, but this depends on 2's complement representation. It makes mask be equal to all 1s if the sign bit is set (since it is being shifted right and this is usually an arithmetic shift, so sign extension occurs). This is equivalent to setting mask to either -1 or 0 according to the sign bit.
  • Isn't right shifting signed ints implementation defined ? Basically we are setting mask = 0x0 for positive and mask=0xffffffff for negative numbers. Isn't "-((unsigned)num>>31)" correct or is it slower ?
  • @ZxcvMnb: Yes, right shifting signed integers is implementation defined. As I mentioned in a previous comment, this is usually an arithmetic right shift (for instance, GCC defines this as such). I don't know if your variation is slower, though it probably requires more operations (i.e. logical shift, negate instead of a single arithmetic shift), in any case, both variations require a 2's complement representation. The linked page has more discussion, which you might find relevant.
  • just doing v * ((v>0) - (v<0)) would be equivalent and easier to read, no?
  • "branch-free" in C, may not be once compiled. To be interesting, "branchfree" really is a property of the object code, not of the source.
  • @SteveJessop: But more seriously: Probably, with any half-decent compiler. However, this is also branchfree in the code structure :)