Can you show us the code that gives -2 when you do 254 & 0xff?
Are you putting the result in a byte? Notice that the range of possible values for the data type byte is -128 to 127. The number 254 doesn't fit in a byte. A byte with the bit pattern 11111110 is interpreted as -2 instead of 254.
Java's lack of an unsigned byte bugs me. I used to enjoy using 0..255 in Pascal. I usually do these bitwise operations in ints (taking care to only use the low 8 bits) then convert to byte only if necessary. At least I can see a value like 254 when I want to.
When you see -2 I bet the right bits are still going to the stream, no?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi