4 ms·
What's the right conversion in this case? How to narrow down negative long to negative int without loosing a sign?
by scotty79 4y ago
What's the right conversion in this case? How to narrow down negative long to negative int without loosing a sign?
- slaymaker1907 4y agoIt could or for integer types less than 4 bytes. For integers, while I don't think Java has this built in, you could use saturating subtraction (so it goes to INT_MIN or something on underflow).
- Dylan16807 4y agoFor this situation you want it to saturate. Clamp the value between int_min and int_max.
- wiml 4y agoI don't know about Java or Go, but any time I've looked at a C compiler's output it's emitted pretty good assembly for "if (a>b) return 1; else if (a<b) return -1; else return 0;" kinds of input when optimization is on. As long as the type being compared is something the compiler can reason about (and/or has a peephole optimization for I guess).
- sltkr 4y agoYou could call Long.signum(), but that's not the right solution here: you should not subtract the values, but call Long.compare(a, b) directly, which is clear, efficient and correct. The reason to avoid subtraction is that you can get integer underflow if one operand is negative and one is positive, and then the result of Long.signum(b - a) is different from Long.compare(a, b).