3 ms·
I'm surprised about the suggested solution for java: int mid = (low + high) >>> 1; I suppose things like this is why the ">>>" (unsigned shift) operator exi
by e12e 9y ago
I'm surprised about the suggested solution for java:
int mid = (low + high) >>> 1;
I suppose things like this is why the ">>>" (unsigned shift) operator exists - but it's a bit odd when the value it works on is considered signed by the language, and implemented as two-compliment signed in memory.
What's interesting to me is that this allows the sum to overflow, and would fail with the ">>" operator as far as I can tell (signed shift) - just like the original code would fail with simply dividing by 2.
Guess it shows java's "system language" roots - in that one might expect there to be a way to be alerted to overflow when working with signed integers - but the solution here is to use a special operator to "fix" the problem.
Maybe it's just me, but it's a solution that would feel more at home in assembler, than I personally think it does in java.
- bradleyjg 9y agoI agree it would be very surprising to see that line in a java codebase. >>> seems more like an answer to a java trivia question than something you'd come across on a regular basis.
- e12e 9y agoThinking a bit more about this, I think what feels off about it to me, is the invisible "type gymnastics" - it's something that might be a bad idea, but feel more natural, in assembly (that byte is what you decide it represents at any given moment). The individual numbers are signed ints, the sum overflows and is treated as an "unsigned two's complement binary" and shifted down to a signed int... It feels like subtle subversion of java's admittedly strange type system for numbers (mix of raw integer types and boxed numbers is never going to be pretty...).