Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Abs for difference of two ulong (unsigned long) values

Tags:

c#

.net

math

I am looking for Math.Abs(ulong,ulong) with return type ulong. But it seems Microsoft only implemented it for long, int and so on. Is there another fast way to do it?

Sorry, need to correct:

Math.Abs(ulong - ulong)

So it can get negative, and be out of the range of a long.

like image 993
Chris Avatar asked Sep 03 '12 20:09

Chris


People also ask

Is math ABS double or int?

abs() method returns the absolute (Positive) value of a int value.

What is Math Abs in c#?

In C#, Abs() is a Math class method which is used to return the absolute value of a specified number. This method can be overload by passing the different type of parameters to it.

How do you find the absolute value of a decimal?

The absolute value of a Decimal is its numeric value without its sign. For example, the absolute value of both 1.2 and -1.2 is 1.2.

How do you make an absolute number in C#?

Abs() method in C# is used to return the absolute value of a specified number in C#. This specified number can be decimal, double, 16-bit signed integer, etc.


2 Answers

Unsigned long values are always positive, as they do not contain a sign. As such, Math.Abs would make no sense for ulong.


Given your new question, you can use:

ulong difference = first > second ? first-second : second-first;

This will give you the difference between the two values, which is effectively the absolute value of the result you'd get by subtracting the two values as if they were signed.

like image 183
Reed Copsey Avatar answered Sep 30 '22 21:09

Reed Copsey


To avoid going out of range I think you want something like this:

a > b ? a-b : b-a
like image 37
Lucero Avatar answered Sep 30 '22 20:09

Lucero