[c#] Convert a positive number to negative in C#

You can convert a negative number to positive like this:

int myInt = System.Math.Abs(-5);

Is there an equivalent method to make a positive number negative?

This question is related to c#

The answer is


int negInt = -System.Math.Abs(myInt)

int myNegInt = System.Math.Abs(myNumber) * (-1);

Just for fun:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "-", positiveInt.ToString()));

Update: the beauty of this approach is that you can easily refactor it into an exception generator:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "thisisthedumbestquestioninstackoverflowhistory", positiveInt.ToString()));

Even though I'm way late to the party here, I'm going to chime in with some useful tricks from my hardware days. All of these assume 2's compliment representation for signed numbers.

int negate = ~i+1;
int positiveMagnitude = (i ^ (i>>31)) - (i>>31);
int negativeMagnitude = (i>>31) - (i ^ (i>>31));

As previously mentioned, just multiplying by -1 is not cool, as int.MinValue * -1 == int.MinValue

It really depends on your application, but for mine (Inverting Joystick axes) I want to ensure that all extremes are still reachable, and maintain as much fidelity as possible.
To this end, I map Max <--> Min and everything in-between gets a * -1
Using this technique, -32767 is unreachable when inverting.

    private static int Invert(int value)
    {
        if (value == int.MaxValue) return int.MinValue;
        if (value == int.MinValue) return int.MaxValue;
        return value * -1;
    }

Converting a number from positive to negative, or negative to positive:

public static decimal Reverse(this decimal source)
{
     return source * decimal.MinusOne;
}

int myInt = - System.Math.Abs(-5);

Note to everyone who responded with

- Math.Abs(myInteger)

or

0 - Math.Abs(myInteger)

or

Math.Abs(myInteger) * -1

as a way to keep negative numbers negative and turn positive ones negative.

This approach has a single flaw. It doesn't work for all integers. The range of Int32 type is from "-231" to "231 - 1." It means there's one more "negative" number. Consequently, Math.Abs(int.MinValue) throws an OverflowException.

The correct way is to use conditional statements:

int neg = n < 0 ? n : -n;

This approach works for "all" integers.


Maybe this?

int n;

.... some coding....

n = n<=0? n:0-n;

Just something that I want to share.

public decimal NumberReevaluate(decimal number, bool isPositive)
{
    var tempNumber = System.Math.Abs(number);
    return isPositive ? tempNumber : -tempNumber;
}

int negInt = 0 - myInt;

Or guaranteed to be negative.

int negInt = -System.Math.Abs(someInt);

X=*-1 may not work on all compilers... since it reads a 'multiply' 'SUBTRACT' 1 instead of NEGATIVE The better alt is X=(0-X), [WHICH IS DIFF FROM X-=X]


Just for more fun:

int myInt = Math.Min(hisInt, -hisInt);

int myInt = -(int)Math.Sqrt(Math.Pow(Math.Sin(1), 2) + Math.Pow(Math.Cos(-1), 2))
            * Math.Abs(hisInt);

The same way you make anything else negative: put a negative sign in front of it.

var positive = 6;
var negative = -positive;

Use binary and to remove the last bit which is responsible for negative sign.

Or use binary or to add sign to a datatype.

This soln may sound absurd and incomplete but I can guarantee this is the fastest method.

If you don't experiment with what I have posted this post may look crap :D

Eg for int:

Int is 32 bit datatype so the last bit (32th one) determines the sign.

And with a value which has 0 in the 32 place and rest 1. It will convert negative no to +ve.

For just the opposite or with a value with 1 in 32th place and rest 0.


I use myInt = -myInt;

So simple and easy

If you want to have only positive

myInt = myInt>0 ? myInt : -myInt;

Multiply it by -1.


EDIT: This is wrong for positive inputs... I made mistake of forgetting that the rest of the bits in -x (2s-Complement value) are the 'opposite' of their value in +x, not the same. SO simply changing the sign bit will NOT work for positive numbers.

I'll leave this here for in for purposes...

Or the tricky way ( I think )...

int y = x | ~int.MaxValue;

cause int.MaxValue is 0111 1111 1111 1111 1111 1111 1111 1111

so

~int.MaxValue is      1000 0000 0000 0000 0000 0000 0000 0000

and therefore any int32 Or'ed with that will put a 1 in the sign bit, (making it negative), and leave all the other bits the same...

EDIT: actually, Since the 1000 0000 0000 0000 0000 0000 0000 0000 is actually the Minvalue, this should also work:

   int y = x | int.MinValue; // or, to do it to itself,
   x |= int.MinValue;

To switch the sign of an integer, you just use the sign operator:

myInt = -myInt;

To make it negative regardless if the original value is negative or not, you first use the Abs method:

myInt = -Math.Abs(myInt);

The easy way:

myInt *= -1;

long negativeNumber = (long)positiveInt - (long)(int.MaxValue + 1);

Nobody said it had to be any particular negative number.