## Forum Stats

• 3,770,515 Users
• 2,253,129 Discussions

Discussions

# How do you Invert signed numbers?

Member Posts: 46,655 Green Ribbon
edited Sep 3, 2009 6:36PM
Hi there.

A simple question: How can I invert the sign of an integer? ie) convert -12 to +12? No doubt there is a really simple way to do this, but I'm stumped, I cannot find anything and I've been working on this program all day.

I'll be very grateful to anyone who can let me know if Java provides a way to do this, or point me in the right direction if it takes some tweaking of binary numbers using the Math package or something.

Cheers!

• Member Posts: 46,655 Green Ribbon
`n = -n`
• Member Posts: 2,678
edited Aug 26, 2009 12:27PM
Is this a joke? If not, try this:
```int x = numberToInvertSign;
boolean pos = x > 0;
for(int i = 0; i < 2*Math.abs(x); i++){
if(pos){
numberToInvertSign--;
}
else{
numberToInvertSign++;
}
}```
• Member Posts: 46,655 Green Ribbon
I knew it would be simple, but not that simple! I feel like a right dumbass now.

Thanks very much paul.miner, you saved the day.
• Member Posts: 46,655 Green Ribbon
No joke, I just tried it and it worked.
• Member Posts: 46,655 Green Ribbon
paul.miner wrote:
`n = -n`
Not obscure enough! I prefer
``` int n = ....;
n = (0xffffffff ^ n) + 1;```
• Member Posts: 46,655 Green Ribbon
sabre150 wrote:
paul.miner wrote:
`n = -n`
Not obscure enough! I prefer
```int n = ....;
n = (0xffffffff ^ n) + 1;```
Meh:
`n = ~n + 1;`
• Member Posts: 46,655 Green Ribbon
Or better:
`n = ~--n;`
• Member Posts: 46,655 Green Ribbon
paul.miner wrote:
Meh:
`n = ~n + 1;`
:-)
• Member Posts: 7,698
sabre150 wrote:
paul.miner wrote:
`n = -n`
Not obscure enough! I prefer
```int n = ....;
n = (0xffffffff ^ n) + 1;```
Bah, that +1 operation is way too clear; better make that:
```n^= 0xffffffff;
int m;
for (m= 1; m != 0 && ((n&m) != 0); m<<= 1);
n|= m;
if (m == 0) n= m;
else for (m >>= 1; m != 0; n^= m, m>>=1);```
kind regards,

Jos ;-)
• Member Posts: 46,655 Green Ribbon
>
`else for (m >>= 1; m != 0; n^= m, m>>=1);`
Shouldn't this be an unsigned shift, at least for the initial shift?
`else for (m >>>= 1; m != 0; n^= m, m>>=1);`
This discussion has been closed.