I spent the better part of a day chasing down a binary reconstruction bug, and want to understand why:
the specific line of code looked like this (dataBuffer
is an array of bytes):
short data = (short) ((short)dataBuffer[curPos + 3] << 8 | ((short)dataBuffer[curPos + 2]));
it sporadically returned garbage until i added a mask to the low-order word:
short data = (short) ((short)dataBuffer[curPos + 3] << 8 | (((short)dataBuffer[curPos + 2])) & 0xff);
so, my interpretation is that the type-cast from byte
to short
occasionally leaves behind trash in the high-order word, causing issues when it's or-ed... but that doesn't make a whole lot of sense.
this code is taken from c++ and worked great there... what am i missing?