I’m dealing with converting floats from CCS, which does not follow the IEEE standard (instead of Sign Bit, Exponent, Mantissa, they use Exponent, Sign Bit, Mantissa); I’ve come across some weird behavior using the >>> operator.
given
byte byte1=(byte)0x8A; //10001010
byte byte2=(byte)(byte1>>>1); //11000101
Since >>> specifies that it will insert a 0 , why am I getting a 1?
I can code around this and just manually flip the bit, but I don’t want to wind up discovering it is platform specific.
In java, bytes are cast to ints automatically before the shift operates on them. Codologically, what you’re doing is equivalent to:
And, of course, casting to int sign extends. If you were to leave the result as an integer, you would see the (then) expected value of 0x7FFFFFC5.
To get around this, just mask the 8th bit flat.
Related question
Isn’t this behavior sensible and expected and isn’t java great?