0

I am trying to convert negative Integer.MIN to positive long value using below code :

long lv = -1 * value_int;

Above code works perfectly except when value of value_int = Integer.MIN_VALUE. In Integer.MIN_VALUE case, value of lv is always Integer.MIN_VALUE;

Below code work in all cases including Integer.MIN_VALUE

long lv = value_int;
lv = -1 * value_int;

Any idea why long lv = -1 * value_int does not work in Integer.MIN_VALUE case?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
abhig
  • 840
  • 2
  • 12
  • 22
  • @Oleg that's a C# question/answer. Although in this case, the problem is likely quite similar, it's not a good duplicate. – Erwin Bolwidt Oct 28 '17 at 13:45
  • 1
    @ErwinBolwidt You're probably right. Found another one https://stackoverflow.com/questions/24755629/int-to-long-assignment though also not a perfect fit. I should probably just stop wasting my time flagging duplicates and answer obvious ones instead, if nobody cares about the quality of content here, why should I? (just ranting, not directed at you) – Oleg Oct 28 '17 at 14:01

1 Answers1

7

1 (preceded by the unary - operator, in this case) is an int literal. Since value_int is also an int, the multiplication is done as an int - which overflows, and only then promoted to a long. If you use a long literal instead, the multiplication will be done as a long, and you'd get the correct result:

long lv = -1L * value_int;
// Here-----^
Mureinik
  • 297,002
  • 52
  • 306
  • 350