Closed Clownacy closed 2 years ago
hmm, doesn't this cause off by one error for negative numbers? like -1 >> 10 = -1, -1 / 1024 = 0
You're right...
There are some suggestions here on how to implement a portable arithmetic right shift, but none of them seem very efficient: https://stackoverflow.com/questions/31879878/how-can-i-perform-arithmetic-right-shift-in-c-in-a-portable-way
Arithmetic right shifting hinges on the idea of repeating the sign bit, which doesn't make sense for signed number representations such as sign-magnitude, so arithmetic right shifting in general isn't strictly portable either as it only makes sense for ones' complement and two's complement.
The only "perfect" solution I can think of is forgoing signed types entirely, and implementing two's complement manually with unsigned integers.
I'd rather leave the arithmetic shifts too. What computer architecture is around that doesn't use 2's complement encoding and that may be used for OPN emulation?
To be honest, this might be a vain effort: there are many more cases of shifting signed integers throughout the codebase, and GCC considers them such a non-issue that it doesn't even have an option for producing compiler warnings when they happen. This might just be one of those cases of something that technically is against the C standard but doesn't harm portability to any significant degree (like assuming that negative signed integers are expressed in binary as two's complement).