Offsetting by 128 is sometimes used in Java to work around byte
being signed. Adding 128 ensures that the result (which will be an int
) is non-negative again. As long as it is symmetric with the encoder (the corresponding writeMessage
), then it is a way to encode unsigned bytes.
After that, the bytes are reassembled into something bigger. That would not work right with signed bytes. By the way I think a pair of parentheses is missing, and the expression should be n1 + ((n3 << 8) + n2 << 8)
, or clearer: n1 + (n2 << 8) + (n3 << 16)
An alternative is using byteValue & 0xFF
to get rid of the leading ones added by sign-extension. That has the benefit that the raw bytes are used "as themselves", without a strange offset.
The inverse is extracting the bytes and offsetting them by 128 again (adding or subtracting 128 would actually do the same thing, but for symmetry it makes more sense to subtract here), for example:
byte n1 = (byte)((size & 0xFF) - 128);
byte n2 = (byte)((size >> 8 & 0xFF) - 128);
byte n3 = (byte)((size >> 16 & 0xFF) - 128);
The & 0xFF
operation is not strictly necessary (the final cast to byte
gets rid of the high bits), but makes it clear that bytes are being extracted.