Recently I must have had a really bad day, because I wrote a very stupid line of code in java:
when I wanted something a little simpler:
It gave unexpected (for me) behavior for shifting negative number of bits. I was having hope that shifting -1 place left would be equal to shifting 1 place right. But I was wrong, and the result was always zero, no matter what number I would try to shift. After a little search I have found: Bitwise and Bit Shift Operators but is says nothing about this case.
So I tried the same code in different languages to check how they behave. I started with my favorite – Ruby:
Here the results were as I would like them to be.
So what does our good, old friend C has to say?
It gives the same results as Java code. So I have to assume that it is described in some specification, or maybe is processor specific as shifting is simple assembler instruction.
Last language I have tried is Ruby companion, Python, which behave more elegantly than C or Java:
It actually checked for nonsensical value and raised an exception not giving me silently wrong (from my perspective) value. Sadly Python does not behave similarly for other basic mistakes, as: