Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to differentiate between 0 and -0?

I know that the integer values 0 and -0 are essentially the same. But, I am wondering if it is possible to differentiate between them.

For example, how do I know if a variable was assigned -0?

bool IsNegative(int num) {     // How ? }  int num = -0; int additinon = 5;  num += (IsNegative(num)) ? -addition : addition; 

Is the value -0 saved in the memory the exact same way as 0?

like image 670
Filip Minx Avatar asked Apr 30 '15 08:04

Filip Minx


1 Answers

It depends on the machine you're targeting.

On a machine that uses a 2's complement representation for integers there's no difference at bit-level between 0 and -0 (they have the same representation)

If your machine used one's complement, you definitely could

0000 0000   -> signed   0  1111 1111   -> signed   −0 

Obviously we're talking about using native support, x86 series processors have native support for the two's complement representation of signed numbers. Using other representations is definitely possible but would probably be less efficient and require more instructions.

(As JerryCoffin also noted: even if one's complement has been considered mostly for historical reasons, signed magnitude representations are still fairly common and do have a separate representation for negative and positive zero)

like image 125
Marco A. Avatar answered Sep 22 '22 01:09

Marco A.